最简单的实现Linux C++多线程的互斥访问

版权声明:如需转载,请注明本作者,邮箱[email protected] https://blog.csdn.net/weixin_38976558/article/details/84592322
#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;

}

猜你喜欢

转载自blog.csdn.net/weixin_38976558/article/details/84592322