Test linux 多线程

本文探讨了使用C++线程库实现线程同步的方法,包括互斥锁、线程函数创建与加入、以及线程间的数据交互。通过具体代码示例展示了如何在多线程环境下确保数据的一致性和正确性。

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

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

class CLock
{
public:

        CLock();
        virtual ~CLock();

        int lock();
        int init();
        int destroy();
        int unlock();

private:
        pthread_mutex_t         lock_;

};


CLock::CLock()
{
        int res =0;
        pthread_mutex_t         lock_;

}

CLock::~CLock()
{
        destroy();

}

int CLock::init()
{
        int res =0;
        res = pthread_mutex_init(&lock_,  NULL);
        return res;

}

int CLock::lock ()
{
        int res =0;
        return pthread_mutex_lock(&lock_);

}
int CLock::unlock()
{
        int res =0;
        return pthread_mutex_unlock(&lock_);

}

int CLock::destroy()
{
        int res =0;
        pthread_mutex_destroy(&lock_);
        return 0;

}


CLock mylock;

void *pthread_function1(void*)
{
        printf("enter the function1:\n");
        mylock.lock();
        printf("the function1 start work\n");
        sleep(5);
        mylock.unlock();
        printf("the function1 stop work\n");
}

void  *pthread_function2(void*)
{
        printf("enter the function2:\n");
        mylock.lock();
        printf("the function2 start work\n");
        sleep(5);
        mylock.unlock();
        printf("the function2 stop work\n");
}

int main ()
{
        printf("Hello World!\n");
        pthread_t t1,t2;
        pthread_create( &t1, NULL,pthread_function1, NULL);
        pthread_create( &t2, NULL,pthread_function2, NULL);
        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        printf("wwwwwwwwww!\n");
        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值