有关多线程的问题,求教

liuxialong 2011-07-01 11:01:53
1 #include <iostream>
2 #include <unistd.h>
3 #include <pthread.h>
4
5 using std::cout;

6 using std::endl;
7
8 static int num=0;
9
10 void clean_up(void *)
11 {
12 num++;
13 }
14
15 void *func(void *)
16 {
17 pthread_cleanup_push(clean_up, NULL);
18 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
19 while(1)
20 {
21 int a=0;
22 }
23 pthread_cleanup_pop(0);
24 return (void *)1;
25 }
26
27 int main(void)
28 {
29 pthread_t tid[1024];
30 for(int i=0; i<1024; i++)
31 {
32 pthread_create(&tid[i], NULL, func, NULL);
33 }
34 sleep(10);
35 for(int i=0; i<1024; i++)
36 {
37 pthread_cancel(tid[i]);
38 }
39 sleep(10);
40 cout<<num<<endl;
41 return 0;
42
43 }

程序执行的结果却是:
terminate called without an active exception
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called recursively
terminate called without an active exception
terminate called recursively
已放弃


不明白,为什么会这样的结果,求高手解答!!!!!

...全文
185 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wyjq395 2011-07-03
  • 打赏
  • 举报
回复

15 void *func(void *)
16 {
17 pthread_cleanup_push(clean_up, NULL);
18 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
19 while(1)
20 {
21 int a=0;
22 }
23 pthread_cleanup_pop(0);
24 return (void *)1;
25 }

这个函数错了,你用while(1)就不会执行到pthread_cleanup_pop(0);
你可以试一试把19到22行注释掉。
金刚葫芦娃 2011-07-01
  • 打赏
  • 举报
回复
改少点看看运行结果.
justkk 2011-07-01
  • 打赏
  • 举报
回复
线程数目太多了吧
1024改为10试试看
liuxialong 2011-07-01
  • 打赏
  • 举报
回复
线程不是从0开始,线程id是用个数组来储存的
[Quote=引用 7 楼 wyjq395 的回复:]

你的线程id怎么从0开始啊,不考虑是不是特殊的线程,也不考虑有没有被占用?
[/Quote]
wyjq395 2011-07-01
  • 打赏
  • 举报
回复
你的线程id怎么从0开始啊,不考虑是不是特殊的线程,也不考虑有没有被占用?
「已注销」 2011-07-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 yanook 的回复:]

删除39行的 sleep(10);
pthread_cancel()堵塞
[/Quote]
不明白你你所说的阻塞,请教。
yanook 2011-07-01
  • 打赏
  • 举报
回复
删除39行的 sleep(10);
pthread_cancel()堵塞
yanook 2011-07-01
  • 打赏
  • 举报
回复
发现两个地方可能有问题:
1.创建线程太多,你可以用ulimit -s 看看每个线程占多大内存,一般是8m 计算一下8m*1024=?
2.pthread_cancel()用法貌似不太对,我的猜测,你可以跟踪一下。
liuxialong 2011-07-01
  • 打赏
  • 举报
回复
改10也一样,只不过terminate called recursively次数少些
[Quote=引用 2 楼 abao623660072 的回复:]

改少点看看运行结果.
[/Quote]

23,116

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧