多线程同步一直是一个难点,利用linux的互斥锁与条件变量实现了两个线程交叉打印数据,并且进行初步封装,可重用
/**************************************************
* 两个线程交叉打印
* ************************************************/
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
class thread {
public:
void thread_init();
void thread_start();
void thread_destroy();
static void* thread_routine1(void*);
static void* thread_routine2(void*);
private:
static pthread_mutex_t mutex;
static pthread_cond_t cond1;
static pthread_cond_t cond2;
};
pthread_mutex_t thread::mutex;
pthread_cond_t thread::cond1;
pthread_cond_t thread::cond2;
static int num = 10;
void* thread::thread_routine1(void* arg)
{
while (num != 0) {
pthread_mutex_lock(&mutex);
if (num % 2 == 0) {
pthread_cond_wait(&cond1, &mutex);
printf("thread1 %d\n", num);
sleep(1);
num--;
} else {
pthread_cond_broadcast(&cond2);
}
pthread_mutex_unlock(&mutex);
}
}
void* thread::thread_routine2(void* arg)
{
while (num != 0) {
pthread_mutex_lock(&mutex);
if (num % 2 != 0) {
pthread_cond_wait(&cond2, &mutex);
printf("thread2 %d\n", num);
sleep(1);
num--;
} else {
pthread_cond_broadcast(&cond1);
}
pthread_mutex_unlock(&mutex);
}
}
void thread::thread_start()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thread_routine1, NULL);
//sleep(1);
pthread_create(&tid2, NULL, thread_routine2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
}
void thread::thread_init()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond1, NULL);
pthread_cond_init(&cond2, NULL);
}
void thread::thread_destroy()
{
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
}
int main()
{
thread t;
t.thread_init();
t.thread_start();
t.thread_destroy();
return 0;
}