小工具知识网

当前位置: 首页 > 行业知识 > 【Linux】线程互斥

行业知识

【Linux】线程互斥

2026-12-02 10:08:43 来源:互联网转载

线程互斥

  • 一、互斥概念
  • 二、互斥锁
    • 1. 互斥锁接口
    • 2. 使用接口以及说明问题
    • 3. 锁的原理
    • 三、可重入和线程安全
    • 四、***锁
      • 1. ***锁概念
      • 2. ***锁的必要条件
      • 3. 避免���锁

        一、互斥概念

        大部分情况,线程使用的数据都是局部变量,变量的地址空间在线程栈空间内,这种情况,变量归属单个线程,其他线程无法获得这种变量。但有时候,很多变量都需要在线程间共享,这样的变量称为共享变量,可以通过数据的共享,完成线程之间的交互。多个线程并发的操作共享变量,会带来一些问题。

        例如下面我们模拟一个多线程抢票的程序。使用一个全局变量 ticket 表示票的数量,创建多个线程进行抢票,代码如下:

        #define NUM 5int ticket = 100;class threadData{public:    threadData(int number)    {        threadname = "thread-" + to_string(number);    }public:    string threadname;};void* getTicket(void* args){    threadData *td = static_cast(args);        while(1)    {        if(ticket > 0)        {            usleep(1000);     // 模拟抢票的时间            printf("%s is running, get a ticket: %d\n", td->threadname.c_str(), ticket);            ticket--;        }        else            break;    }    return nullptr;}int main(){    vector tids;    vector thread_datas;    for(int i = 1; i  0)        {            usleep(1000);       // 模拟抢票的时间            printf("%s is running, get a ticket: %d\n", td->_threadname.c_str(), ticket);            ticket--;            pthread_mutex_unlock(td->_lock);            usleep(10);        }        else        {            pthread_mutex_unlock(td->_lock);            break;        }    }    cout _threadname.c_str() 

上一篇:怎么进入ibm云服务器?

下一篇:Flipfap下载攻略,一键获取应用操作教程