void* say_hello( void* args ) { int i = *( (int*)args ); //对传入的参数进行强制类型转换,由无类型指针转变为整形指针,再用*读取其指向到内容 cout << "hello in " << i << endl; returnNULL; } //函数返回的是函数指针,便于后面作为参数
intmain() { pthread_t tids[NUM_THREADS]; //线程id cout << "hello in main.." << endl; for( int i = 0; i < NUM_THREADS; ++i ) { int ret = pthread_create( &tids[i], NULL, say_hello, (void*)&i ); //传入到参数必须强转为void*类型,即无类型指针,&i表示取i的地址,即指向i的指针 cout << "Current pthread id = " << tids[i] << endl; //用tids数组打印创建的进程id信息 if( ret != 0 ) //创建线程成功返回0 { cout << "pthread_create error:error_code=" << ret << endl; } } pthread_exit( NULL ); //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态 return0; }
测试结果:
1 2 3 4 5 6 7 8 9 10 11 12
jack@jack:~/coding/muti_thread$ ./pthread_chap2 hello in main.. Current pthread id = 3078458224 Current pthread id = 3070065520 hello in hello in 2 1 Current pthread id = hello in 2 3061672816 Current pthread id = 3053280112 hello in 4 Current pthread id = hello in 4 3044887408
for( int i = 0; i < NUM_THREADS; ++i ) { indexes[i] = i; int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) ); //5个进程同时去修改sum if( ret != 0 ) { cout << "pthread_create error:error_code=" << ret << endl; } } pthread_attr_destroy( &attr ); //释放内存 void *status; for( int i = 0; i < NUM_THREADS; ++i ) { int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status if( ret != 0 ) { cout << "pthread_join error:error_code=" << ret << endl; } } cout << "finally sum is " << sum << endl; pthread_mutex_destroy( &sum_mutex ); //注销锁 return0; }
测试结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
jack@jack:~/coding/muti_thread$ ./pthread_chap5 hello in thread hello in thread hello in thread 410 before sum is hello in thread 0 in thread 4 after sum is 4 in thread 4hello in thread
2 3 before sum is 4 in thread 1 after sum is 5 in thread 1 before sum is 5 in thread 0 after sum is 5 in thread 0 before sum is 5 in thread 2 after sum is 7 in thread 2 before sum is 7 in thread 3 after sum is 10 in thread 3 finally sum is 10
jack@jack:~/coding/muti_thread$ ./pthread_chap6 [3069823856] hello in thread 2 [3078216560] hello in thread 1[3069823856] take task: 10 in thread 2
[3069823856] take task: 9 in thread 2 [3069823856] take task: 8 in thread 2 [3069823856] take task: 7 in thread 2 [3069823856] take task: 6 in thread 2 [3069823856] pthread_cond_signal in thread 2 [3078216560] take task: 5 in thread 1 [3078216560] take task: 4 in thread 1 [3078216560] take task: 3 in thread 1 [3078216560] take task: 2 in thread 1 [3078216560] take task: 1 in thread 1