c语言线程锁的原理开锁原理图,C++多线程之可重入锁

#include

#include

#include

using namespace std;

recursive_mutex re;

void task1()

{

re.lock();

cout << "处理任务1中..." << endl;

std::this_thread::sleep_for(1s);

re.unlock();

}

void task2()

{

re.lock();

cout << "处理任务2中..." << endl;

std::this_thread::sleep_for(1s);

re.unlock();

}

class ThreadBase

{

public:

virtual void Start()

{

is_exit = false;

th = std::thread(&ThreadBase::Main,this);

}

virtual void Stop()

{

is_exit = true;

Wait();

}

virtual void Wait()

{

if (th.joinable())

{

th.join();

}

}

bool get_exit()

{

return is_exit;

}

virtual void Main() = 0;

ThreadBase(int _i):i(_i) {}

virtual ~ThreadBase() {}

int i;

private:

std::thread th;

bool is_exit;

};

class MyThread:public ThreadBase

{

public:

MyThread(int i):ThreadBase(i) {}

~MyThread() override {}

void Main() override

{

for (;;)

{

//如果不是可重入锁,那么得先开锁然后才能执行task1,否则会造成死锁

//但是如果开锁,也就是在一个线程执行任务时,另一个线程也进来了,如果另一个线程执行了一会就结束了,肯定会

//释放锁,而实际上线程一的任务还没执行完

re.lock();

cout << "线程" << i << "拿到了锁" << endl;

task1();

task2();

re.unlock();

std::this_thread::sleep_for(1ms);

}

}

};

int main(int argc,char* argv[])

{

MyThread th_one(1);

th_one.Start();

th_one.Wait();

getchar();

return 0;

}

原文:https://www.cnblogs.com/SunShine-gzw/p/14530107.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言线程互斥锁是一种同步机制,用于协调多个线程之间的访问共享资源。在多线程程序,如果多个线程同时访问同一个共享资源,会导致数据竞争和不确定性结果。为了避免这种情况,我们需要使用互斥锁来确保在任何给定时刻只有一个线程可以访问共享资源。 以下是使用C语言线程互斥锁的基本步骤: 1.包含头文件:需要包含头文件< pthread.h>,该头文件包含了互斥锁相关的函数定义。 2.定义互斥锁:使用 pthread_mutex_t 数据类型定义互斥锁。 3.初始化互斥锁:使用 pthread_mutex_init() 函数初始化互斥锁。 4.加锁:使用 pthread_mutex_lock() 函数加锁,确保只有一个线程可以访问临界区。 5.解锁:使用 pthread_mutex_unlock() 函数解锁,允许其他线程访问临界区。 6.销毁互斥锁:使用 pthread_mutex_destroy() 函数销毁互斥锁。 下面是一个简单的示例程序,展示了如何使用互斥锁来保护共享变量: ```c #include <pthread.h> #include <stdio.h> pthread_mutex_t mutex; int count = 0; void* increment(void* arg) { int i; for (i = 0; i < 10000; i++) { pthread_mutex_lock(&mutex); count++; pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t thread1, thread2; // 初始化互斥锁 pthread_mutex_init(&mutex, NULL); // 创建线程 pthread_create(&thread1, NULL, increment, NULL); pthread_create(&thread2, NULL, increment, NULL); // 等待线程结束 pthread_join(thread1, NULL); pthread_join(thread2, NULL); // 销毁互斥锁 pthread_mutex_destroy(&mutex); printf("Count: %d\n", count); return 0; } ``` 在上面的示例程序,我们定义了一个名为 count 的共享变量,并创建了两个线程来对其进行加法操作。在每个线程的循环,我们使用 pthread_mutex_lock() 函数来锁定互斥锁,以确保每个线程都可以独立访问临界区。在 count 变量更新后,我们使用 pthread_mutex_unlock() 函数来解锁互斥锁,允许其他线程访问临界区。最后,我们使用 pthread_mutex_destroy() 函数销毁互斥锁,并输出最终的 count 值。 通过使用互斥锁,我们可以确保多个线程之间的共享资源访问是安全和有序的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值