Linux之线程同步

慈云数据 1年前 (2024-03-25) 技术支持 75 0

目录

一、问题引入

二、实现线程同步的方案——条件变量

1、常用接口

2、使用示例


一、问题引入

我们再次看看上次讲到的多线程抢票的代码:这次我们让一个线程抢完票之后不去做任何事。

#include 
#include 
#include 
#include 
#include 
using namespace std;
#define THREAD_NUM 5
class threaddata
{
public:
    threaddata(const string &s, pthread_mutex_t *m)
        : name(s), mtx(m)
    {}
public:
    string name;
    pthread_mutex_t *mtx;
};
int ticket = 100;
void *getticket(void *arg)
{
    threaddata *td = (threaddata *)arg;
    while (true)
    {
        pthread_mutex_lock(td->mtx); 
        if (ticket > 0)              
        {
            usleep(rand() % 10000);
            cout name cond_, td->mtx_); // 在加锁和解锁之间进行等待
        if (ticket > 0)
        {
            usleep(rand() % 10000);
            cout name_ 
微信扫一扫加客服

微信扫一扫加客服