2012年3月18日 星期日

如何用 pthread 來傳值呢

請看這篇網誌


http://pccts.blogspot.com/2007/11/pthreadcreate.html


// You can use the last parameter of pthread_create() to pass arguments
// The following is an example of it.

#include
#include

void *thread_function(void *);

int main() {
pthread_t thread_id[3];
int i,id[3];

for (i=0; i<3; i++) {
id[i] = i;
pthread_create( &thread_id[i], NULL, thread_function, &id[i] );
}

for (i=0; i<3; i++) {
pthread_join( thread_id[i], NULL);
}
}

void *thread_function( void *arg )
{
int id = *((int *) arg); 宣告變數 去接這個傳進來的值 右邊是 取 int指標arg的 值
int i;

if ( id == 0 ) {
printf("I am 0\n");
} else if ( id == 1 ) {
printf("I am 1\n");
} else {
printf("I am 2\n");
}
return arg;
}

2012年2月8日 星期三

pthread_create ()

1 pthread_create(&Thread_ID , attribute, Void * function (void *) , &value )

創造一個 pthread 一定需要的函式
第一個是 pthread 的名字
第二個是 pthread 的特徵 => 待續
第三個是 pthread 要做的 function 注意 這個 function 一定要是 接收 void * 變數 和 回傳 void * 的變數
第四個 是 這個 function 所需要的 參數


example



#include
#include
#include
#include


void *funct(void *arg )
{
printf( " hello this is thread");

}

int main()
{

pthread_t thread_a;
pthread_create(&thread_a, NULL, funct, NULL );
pthread_join (thread_a,NULL); //等待 thread 被執行完畢

printf("the sub-thread has done");
return 0;

}

pthread

一个线程不能被多个线程等待