|
|

楼主 |
发表于 2005-3-30 16:42:06
|
显示全部楼层
不过就算是让新创建的线程先运行然后再调用pthread_cancel,还是会有问题。以下是对上面的这段程序的修改
- #include <iostream>
- using namespace std;
- #include <pthread.h>
- pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
- pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
- bool flag=true;
- void *thread_run(void *)
- {
- int state;
- pthread_mutex_lock(&mutex);
- pthread_cond_signal(&cond);
- cout<<"------------send a signal"<<endl;
- pthread_mutex_unlock(&mutex);
- cout<<"------------thread start"<<endl;
- while(true){
- pthread_setcancelstate(PTHREAD_CANCEL_DISABLE , &state);
- cout<<"-----------thread loop"<<endl;
- for(int i=0 ; i < 10000 ; i++);
- cout<<"----------start to sleep"<<endl;
- pthread_setcancelstate(state , &state);//enable to cancel the thread
- sleep(1);
- }
- }
- int main()
- {
- for(int i=0 ; i < 1000 ; i++){
- pthread_t id;
- cout<<"create a thread:"<<i<<endl;
- pthread_mutex_lock(&mutex);
- pthread_create(&id , NULL , thread_run , NULL);
- cout<<"start to wait"<<endl;
- pthread_cond_wait(&cond , &mutex);
- pthread_mutex_unlock(&mutex);
- //cout<<"wait for the new thread to run"<<end;
- //pthread_cond_wait(&cond , &mutex);
- cout<<"cancel a thread"<<endl;
- pthread_cancel(id);
- void *reval;
- cout<<"wait for a thread to die"<<endl;
- pthread_join(id , &reval);
- cout<<endl<<endl;
- }
- }
复制代码
这段程序照样不能正常的cancel掉新创建的线程 |
|