linux多线程之mutex

pthread中的mutex有4种操作
pthread_mutex_init[初始化],pthread_mutex_lock[加锁],pthread_mutex_unlock[解锁],pthread_mutex_destory[销毁]

用一段简单的代码实例来说明 线程thread使用mutex阻塞main函数。

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;

void  *thread(void *ptr)
{

    pthread_mutex_lock(&m);
    cout <<"pthread lock &m sucessfully "<< endl;

    sleep(10);
    pthread_mutex_unlock(&m);
    cout <<"pthread unlock &m sucessfully"<< endl;
    return NULL;
}

int main(int argc, char ** argv)
{
    pthread_t id;
    int ret=pthread_create( &id,NULL,thread,NULL);
    if(ret)
    {
        cout <<"thread create error" << endl;
        return 1;
    }

    sleep(1);
    cout <<"the main function waiting ptread unlock mutex m"<< endl;
    pthread_mutex_lock(&m);
    cout <<"main function lock m seccessfully"<< endl;

    pthread_mutex_unlock(&m);
    cout <<"main thread unlock &m sucessfully "<< endl;
    pthread_join(id,NULL);
    pthread_mutex_destroy(&m);
    cout <<"the main function destroy mutex m"<< endl;
    return 0;

}

猜你喜欢

转载自blog.csdn.net/sun_ashe/article/details/77816928