1. 程式人生 > >最簡單的實現Linux C++多執行緒的互斥訪問

最簡單的實現Linux C++多執行緒的互斥訪問

#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
using namespace std;

//定義一個全域性的互斥變數
pthread_mutex_t mut;

//定義全域性變數
int count_ = 0;


void *func_10(void *arg)
{

    for(int i=0;i<10;i++)
    {
        pthread_mutex_lock(&mut);
        count_+=1;
        cout<<"func*____"<<count_<<endl;
        pthread_mutex_unlock(&mut);
        //sleep(300);
    }

}

void *func_20(void *arg)
{

    for(int i=0;i<20;i++)
    {
        pthread_mutex_lock(&mut);
        count_+=1;
        cout<<"func#____"<<count_<<endl;
        //sleep(200);
        pthread_mutex_unlock(&mut);

    }


}

int main()
{
    pthread_t *t1=new pthread_t;
    pthread_t *t2=new pthread_t;

    //建立執行緒
    if (pthread_create(t1, NULL, func_10,NULL) != 0)
    {
       cout<<"create thread is failed ! error message :"<<strerror(errno)<<endl;
        return -1;
    }

    if (pthread_create(t2, NULL, func_20,NULL) != 0)
    {
        cout<<"create thread is failed ! error message :"<<strerror(errno)<<endl;
        return -1;
    }
    pthread_join(*t1,NULL);
    pthread_join(*t2,NULL);

    return 0;

}