多线程同步一直是一个难点,利用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;
}
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t condA;
pthread_cond_t condB;
int number = 0;
void* threadCallbackA(void* arg)
{
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
if (number % 2 == 1) {
cout << number << endl;
number++;
pthread_cond_signal(&condB);
} else {
pthread_cond_wait(&condA, &mutex);
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* threadCallbackB(void* arg)
{
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
if (number % 2 == 0) {
cout << number << endl;
number++;
pthread_cond_signal(&condA);
} else {
pthread_cond_wait(&condB, &mutex);
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t threadA;
pthread_t threadB;
pthread_cond_init(&condA, NULL);
pthread_cond_init(&condB, NULL);
pthread_create(&threadA, NULL, threadCallbackA, NULL);
pthread_create(&threadB, NULL, threadCallbackB, NULL);
//sleep(2);
pthread_join(threadA, NULL);
cout << "thread" << endl;
pthread_join(threadB, NULL);
pthread_exit(&threadA);
pthread_exit(&threadB);
}