LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: icoming

gtk编程遇到一个让我不知所措的错误

[复制链接]
 楼主| 发表于 2005-3-30 16:42:06 | 显示全部楼层
不过就算是让新创建的线程先运行然后再调用pthread_cancel,还是会有问题。以下是对上面的这段程序的修改

  1. #include <iostream>
  2. using namespace std;
  3. #include <pthread.h>

  4. pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
  5. pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
  6. bool flag=true;

  7. void *thread_run(void *)
  8. {
  9.     int state;
  10.     pthread_mutex_lock(&mutex);
  11.     pthread_cond_signal(&cond);
  12.     cout<<"------------send a signal"<<endl;
  13.     pthread_mutex_unlock(&mutex);
  14.     cout<<"------------thread start"<<endl;
  15.     while(true){
  16.         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE , &state);
  17.         cout<<"-----------thread loop"<<endl;
  18.         for(int i=0 ; i < 10000 ; i++);
  19.         cout<<"----------start to sleep"<<endl;
  20.         pthread_setcancelstate(state , &state);//enable to cancel the thread
  21.         sleep(1);
  22.     }
  23. }

  24. int main()
  25. {
  26.     for(int i=0 ; i < 1000 ; i++){
  27.         pthread_t id;
  28.         cout<<"create a thread:"<<i<<endl;
  29.         pthread_mutex_lock(&mutex);
  30.         pthread_create(&id , NULL , thread_run , NULL);
  31.         cout<<"start to wait"<<endl;
  32.         pthread_cond_wait(&cond , &mutex);
  33.         pthread_mutex_unlock(&mutex);
  34.         //cout<<"wait for the new thread to run"<<end;
  35.         //pthread_cond_wait(&cond , &mutex);
  36.         cout<<"cancel a thread"<<endl;
  37.         pthread_cancel(id);
  38.         void *reval;
  39.         cout<<"wait for a thread to die"<<endl;
  40.         pthread_join(id , &reval);
  41.         cout<<endl<<endl;
  42.     }
  43. }
复制代码

这段程序照样不能正常的cancel掉新创建的线程
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-3-30 16:46:12 | 显示全部楼层
但是,如果把thread_run函数改成如下,就不会有问题了。
我发现好像只有在调用像sleep()这样的函数(会让线程挂起的函数)的时候被cancel掉,才能整个程序才能正常运行。我不明白为什么会这样。
请大牛指教

  1. void *thread_run(void *)
  2. {
  3.     int state;
  4.     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE , &state);
  5.     pthread_mutex_lock(&mutex);
  6.     pthread_cond_signal(&cond);
  7.     cout<<"------------send a signal"<<endl;
  8.     pthread_mutex_unlock(&mutex);
  9.     cout<<"------------thread start"<<endl;
  10.     while(true){
  11.         cout<<"-----------thread loop"<<endl;
  12.         for(int i=0 ; i < 10000 ; i++);
  13.         cout<<"----------start to sleep"<<endl;
  14.         pthread_setcancelstate(state , &state);//enable to cancel the thread
  15.         sleep(1);
  16.         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE , &state);//disable to cancel the thread
  17.     }
  18. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表