64,650
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
pthread_t IDA;
pthread_t IDB;
struct _status
{
int running;
int value;
};
_status status;
void *testA(void *param)
{
while(1)
{
sleep(10);
printf("shut down thread B..\n");
status.running = 0;
sleep(10);
status.running = 1;
printf("start thread B..\n");
}
}
void *testB(void *param)
{
while(status.running)
{
printf("thread B is running...\n");
sleep(1);
}
}
int main(int argc, char *argv[])
{
status.running = 1;
pthread_create(&IDA, NULL, testA, NULL);
pthread_create(&IDB, NULL, testB, NULL);
pthread_join(IDA, NULL);
pthread_join(IDB, NULL);
return 0;
}
程序运行结果如下,
thread B is running...
thread B is running...
thread B is running...
thread B is running...
shut down thread B..
start thread B..
shut down thread B..
start thread B..
这是上面问题的总结
为什么线程B中的内容没有被再次运行呢?#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
pthread_t IDA;
pthread_t IDB;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
#define RUN 1
#define STOP 0
int status = RUN;
void * thread_function(void *param)
{
static int i = 0;
while (1)
{
pthread_mutex_lock(&mut);
while (!status)
{
pthread_cond_wait(&cond, &mut);
}
pthread_mutex_unlock(&mut);
//do actual something
printf("thread is running...\n");
sleep(1);
}
}
void thread_resume()
{
if (status == STOP)
{
pthread_mutex_lock(&mut);
status = RUN;
pthread_cond_signal(&cond);
printf("pthread run!\n");
pthread_mutex_unlock(&mut);
}
}
void thread_pause()
{
if (status == RUN)
{
pthread_mutex_lock(&mut);
status = STOP;
printf("thread stop!\n");
pthread_mutex_unlock(&mut);
}
}
void *test(void *param)
{
while(1)
{
sleep(5);
thread_pause();
sleep(10);
thread_resume();
sleep(5);
}
}
int main(int argc, char *argv[])
{
pthread_create(&IDA, NULL, test, NULL);
pthread_create(&IDB, NULL, thread_function, NULL);
pthread_join(IDA, NULL);
pthread_join(IDB, NULL);
return 0;
}