- 论坛徽章:
- 0
|
- pthread_mutex_t mutex;
- struct TEST {
- char str[10];
- int num;
- };
- void dispatch_threadpool_to_me(void *arg) {
- pthread_mutex_lock( &mutex );
- TEST test;
- /*为传入的结构体变量复制一个副本*/
- memcpy( &test, ( TEST* )arg, sizeof( TEST ) );
- pthread_mutex_unlock( &mutex );
- sleep(4);
- printf( "%s,%d\n", test.str, test.num );
- }
- int main(int argc, char **argv) {
- threadpool tp;
- TEST test;
- /*初始化互斥量*/
- if ( pthread_mutex_init( &mutex, NULL ) == 0 )
- {
- printf( "pthread_mutex_init ok\n" );
- }
- else
- {
- return 0;
- }
- /*线程池最大工作线程为10个*/
- tp = create_threadpool(10);
- for ( int i = 0; i < 100; i++ )
- {
- sprintf( test.str, "%d", i );
- test.num = i;
- /*投入线程*/
- dispatch_threadpool(tp, dispatch_threadpool_to_me, (void *) &test );
- }
- /*销毁线程池*/
- destroy_threadpool( tp );
- }
复制代码 打印结果:
0,0
1,1
2,2
3,3
4,4
5,5
6,6
7,7
8,8
9,9
20,20
20,20
20,20
20,20
20,20
20,20
20,20
20,20
20,20
20,20
这段代码的问题出在dispatch_threadpool_to_me线程函数的printf中,现象为printf为重复打印 i 的值。但是我已经使用互斥量来保证每个线程函数中都有一个独立的结构体副本,为什么还会出现这样的问题呢? |
|