免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3172 | 回复: 1
打印 上一主题 下一主题

向线程池中线程函数传递结构体参数的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-05-21 13:47 |只看该作者 |倒序浏览
  1. pthread_mutex_t mutex;

  2. struct TEST {
  3.     char str[10];
  4.     int num;
  5. };

  6. void dispatch_threadpool_to_me(void *arg) {
  7.     pthread_mutex_lock( &mutex );
  8.     TEST test;
  9.     /*为传入的结构体变量复制一个副本*/
  10.     memcpy( &test, ( TEST* )arg, sizeof( TEST ) );
  11.     pthread_mutex_unlock( &mutex );
  12.     sleep(4);
  13.     printf( "%s,%d\n", test.str, test.num );
  14. }


  15. int main(int argc, char **argv) {
  16.   threadpool tp;
  17.   TEST test;

  18.   /*初始化互斥量*/
  19.   if ( pthread_mutex_init( &mutex, NULL ) == 0 )
  20.   {
  21.       printf( "pthread_mutex_init ok\n" );
  22.   }
  23.   else
  24.   {
  25.       return 0;
  26.   }
  27.   /*线程池最大工作线程为10个*/
  28.   tp = create_threadpool(10);

  29.   for ( int i = 0; i < 100; i++ )
  30.   {
  31.       sprintf( test.str, "%d", i );
  32.       test.num = i;
  33.       /*投入线程*/
  34.       dispatch_threadpool(tp, dispatch_threadpool_to_me, (void *) &test );
  35.   }
  36.   /*销毁线程池*/
  37.   destroy_threadpool( tp );

  38. }
复制代码
打印结果:

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 的值。但是我已经使用互斥量来保证每个线程函数中都有一个独立的结构体副本,为什么还会出现这样的问题呢?

论坛徽章:
0
2 [报告]
发表于 2011-05-23 18:56 |只看该作者
用同一个结构体,肯定会有问题,第N个线程可能还没打印,第N+1个已经把它修改了。
100个线程就100哥TEST对象吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP