65,186
社区成员




#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;
}