学习笔记 c++ (linux pthread C++ 多线程互斥锁)

本文详细介绍了如何在C++中使用pthread库创建线程,并通过互斥锁实现线程间的同步。包括pthread_create、pthread_join、pthread_mutex_init等函数的使用,以及编译时链接pthread库的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要引用头文件 <pthread.h>

 

pthread_create(&thread1,NULL,(void *)&dealfunction,NULL); //创建线程

thread1声明格式:pthread_t thread1。

NULL:表示线程属性的指针,可默认为NULL。

dealfunction声明格式:void dealfunction()。返回值可以为其它,可以有参数。

NULL:处理函数的参数指针。

 

pthread_join(thread1,NULL); //阻塞当前线程,立即执行线程1。

 

pthread_mutex_init(&mutex1,NULL); //初始化互斥锁

mutex1声明格式:pthread_mutex_t mutex1。

NULL:互斥锁属性。

 

pthread_mutex_destroy(&mutex1); //释放锁资源。

 

pthread_mutex_lock(&mutex1); //加锁

pthread_mutex_unlock(&mutex1); //去锁

 

在代码中使用pthread,进行编译时,需要使用命令 gcc -o hello hello.c -lpthread

-lpthread 必须要有,否则会报 undefined reference to 'pthread_create'等错误。

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

using namespace std;

pthread_mutex_t mutex1;

void *myid1(void *arg)
{
    pthread_mutex_lock(&mutex1);//上锁
    for(int i=0;i<5;i++)
    {
        sleep(1);
        cout<<"myid111111"<<endl;
    }
    pthread_mutex_unlock(&mutex1);//开锁
}

void *myid2(void *arg)
{
    //pthread_mutex_lock(&mutex1);
    for(int i=0;i<5;i++)
    {
        sleep(1);
        cout<<"myid222222"<<endl;
    }
    //pthread_mutex_unlock(&mutex1);
}

void *myid3(void *arg)
{
    pthread_mutex_lock(&mutex1);
    for(int i=0;i<5;i++)
    {
        sleep(1);
        cout<<"myid333333"<<endl;
    }
    pthread_mutex_unlock(&mutex1);
}

int main(int argc, char** argv)
{
    pthread_t id1,id2,id3;
    pthread_mutex_init(&mutex1,NULL);//初始化互斥锁
    
    pthread_create(&id1,NULL,myid1,NULL);
    pthread_create(&id2,NULL,myid2,NULL);
    pthread_create(&id3,NULL,myid3,NULL);    
    
    pthread_exit(&id1);
    pthread_exit(&id2);
    pthread_exit(&id3);

    pthread_mutex_destroy(&mutex1);//释放互斥锁
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值