线程同步

互斥量:用pthread_mutex_t数据类型来表示,在使用互斥变量以前,必须首先对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy.

改写了个以前的程序:
#include<iostream>
#include<QThread>
#include<QMutex>
#include<QWaitCondition>
#include<pthread.h>
using namespace std;

QMutex mutex;
QWaitCondition wait1;
pthread_mutex_t tid = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

class Thread1:public QThread{
public:
    void run(){
        //mutex.lock();
        pthread_mutex_lock(&tid);
        for(int i=0;i<5;i++){
            msleep(500);
            cout << "t1" << endl;
        }
        pthread_mutex_unlock(&tid);
        //mutex.unlock();
        //wait1.wakeOne();
        pthread_cond_signal(&cond);
    }
};

class Thread2:public QThread{
public:
    void run(){
        //wait1.wait(&mutex);
        pthread_cond_wait(&cond,&tid);
        for(int i=0;i<5;i++){
            cout << "t2" << endl;
        }
    }
};

int main(){
    Thread1 t1;
    Thread2 t2;
    t1.start();
    t2.start();
    t1.wait();
    t2.wait();
}

t1
t1
t1
t1
t2
t2
t2
t2
t2

你可能感兴趣的:(线程同步)