日期:2014-05-16 浏览次数:20803 次
void CPrcThread <Worker>::suspend() { ifdef WIN32 //do windows specific things here... #endif #ifdef __linux__ pthread_mutex_lock(&mutex); flag--; pthread_mutex_unlock(&mutex); #endif } void CPrcThread <Worker>::resume() { #ifdef WIN32 //do windows specific things here... #endif #ifdef __linux__ pthread_mutex_lock(&mutex); flag++; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); #endif } void* CPrcThread <Worker>::threadFunc(void* pParameter) { while(1) { #ifdef WIN32 //do windows specific things here... //no member variables accessed here so its ok... #endif #ifdef __linux__ pthread_mutex_lock(&mutex); while(flag <= 0) { pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex); #endif //actual thread work here } }
------解决方案--------------------
这个我也想实现,知道了告诉我哦
------解决方案--------------------
我来贴个代码
实现原理是
1.定义一个全局的互斥锁mp,在主线程中(main函数里)申请mp(在创建各个线程之前)
2.当要挂起pthread1线程时,主线程发送信号SIGUSR1给线程pthread1
3.在pthread1线程安装的信号处理函数中申请互斥锁mp(当然申请不到了,因为在主线程中以申请了),pthread1被阻塞
4.当要唤醒pthread1时释放互斥锁mp即可
代码如下:
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <semaphore.h> void * thread1(void); void * thread2(void); void thread1_suspend(void); pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t p1; pthread_mutex_lock(&mp); pthread_create(&p1, NULL, (void *)thread1, NULL); sleep(5); printf("main thread kill SIGUSR1\n"); fflush(stdout); pthread_kill(p1, SIGUSR1); sleep(5); pthread_mutex_unlock(&mp); //pthread_kill(p1, SIGCONT); pthread_mutex_destroy(&mp); for(;;); //pthread_join(p1, NULL); //pthread_join(p2, NULL); } void * thread1(void) { int i = 0,j=0,k=0; signal(SIGUSR1, thread1_suspend); for(;;) { printf("thread1 is running! i=%d, j=%d, k=%d\n", i, j, k); k++; fflush(stdout); for(i=0; i<10000; i++) for(j=0; j<10000; j++); } } void thread1_suspend(void) { printf("thread1_suspend lock mutex\n"); pthread_mutex_lock(&mp); printf("thread1_suspend unlock mutex\n"); pthread_mutex_unlock(&mp); }
------解决方案--------------------
是个思路,简单的逻辑应该可以
收到信号时,线程中需要注意对关键代码的保护
另外,如果被停止的线程持有其它线程需要的另外一个锁..
------解决方案--------------------
最好还是如ls某位的用cond通知线程挂起or退出,太暴力了不好啊
------解决方案--------------------