我是mac新手編程,我真的很驚訝大中央調度。我閱讀了這篇文章,看起來像是並行編程的完美解決方案。我使用POSIX線程並想要移至GCD。大中央調度簡單的例子
我在Apple Developer Connection中看到了示例代碼,但它讓我非常困惑。我搜索了一個簡單的例子,用兩個線程開始,但我找不到它。
如何使用GCD做這個示例代碼?
#include <stdio.h> /* standard I/O routines */
#include <pthread.h> /* pthread functions and data structures */
/* function to be executed by the new thread */
void* do_loop(void* data)
{
int i; /* counter, to print numbers */
int j; /* counter, for delay */
int me = *((int*)data); /* thread identifying number */
for (i=0; i<10; i++)
{
for (j=0; j<500000; j++) /* delay loop */
;
printf("'%d' - Got '%d'\n", me, i);
}
/* terminate the thread */
pthread_exit(NULL);
}
void* th2(void* data)
{
cout << "Thread nº 2" << endl;
}
int main(int argc, char* argv[])
{
int thr_id; /* thread ID for the newly created thread */
pthread_t p_thread1;
pthread_t p_thread2; /* thread's structure */
int a = 1; /* thread 1 identifying number */
int b = 2; /* thread 2 identifying number */
/* create a new thread that will execute 'do_loop()' */
thr_id = pthread_create(&p_thread1, NULL, do_loop, (void*)&a);
/* run 'do_loop()' in the main thread as well */
thr_id = pthread_create(&p_thread2, NULL, th2, (void*)&b);
return 0;
}
在此先感謝
是的,喬納森你是對的。我忘了在主程序中放入我的例子'pthread_join'指令,等待線程結束以結束主程序。很多指令相當於GCD的'pthread_join'。非常感謝你的回答。這對我很有幫助。 – 2011-04-01 09:21:21