多线程常识相关

https://blog.csdn.net/dxyt2002/article/details/130209169

#include <iostream>
#include <unistd.h>
#include <pthread.h>
using std::cout;
using std::endl;

int tickets = 10000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;		// 定义全局锁, 并用宏来初始化

void* grabTicket(void* args) {
    const char* name = static_cast<const char*>(args);

    while (true) {
        pthread_mutex_lock(&mutex); // 在即将进入临界区时加锁
        if (tickets > 0) {
            printf("%s: %lu 抢到票了, 编号为: %d\n", name, pthread_self(), tickets--);
            pthread_mutex_unlock(&mutex); // 在即将离开临界区时解锁
            usleep(10);
        }
        else {
            printf("没有票了, %s: %lu 放弃抢票\n", name, pthread_self());
            pthread_mutex_unlock(&mutex); // 在线程即将退出时解锁
            break;
        }
    }

    return nullptr;
}

int main() {
    pthread_t tid1, tid2, tid3, tid4;

    pthread_create(&tid1, nullptr, grabTicket, (void*)"thread_1");
    pthread_create(&tid2, nullptr, grabTicket, (void*)"thread_2");
    pthread_create(&tid3, nullptr, grabTicket, (void*)"thread_3");
    pthread_create(&tid4, nullptr, grabTicket, (void*)"thread_4");

    pthread_join(tid1, nullptr);
    cout << "main thread join thread_1" << endl;
    pthread_join(tid2, nullptr);
    cout << "main thread join thread_2" << endl;
    pthread_join(tid3, nullptr);
    cout << "main thread join thread_3" << endl;
    pthread_join(tid4, nullptr);
    cout << "main thread join thread_4" << endl;

    return 0;
}

这里运行的结果是:
所有票被抢完以后,才依次输出
cout << “main thread join thread_1” << endl;
cout << “main thread join thread_2” << endl;
cout << “main thread join thread_3” << endl;
cout << “main thread join thread_4” << endl;
因为join 限制了一个线程退出以后,才会执行join以后的代码。
但是pthread_create以后,每个线程都已经开始了。他们和主线程是并行的。
如果是detach,那么
cout << “main thread join thread_1” << endl;
cout << “main thread join thread_2” << endl;
cout << “main thread join thread_3” << endl;
cout << “main thread join thread_4” << endl;
这几句话会交错掺杂在抢票结果过程中。抢票未结束的时候主线程就已经退出了。因为进程结束,所以所有线程都杀死。

相关推荐

  1. 线常识相关

    2024-04-03 01:36:02       14 阅读
  2. 【Linux】线相关问题

    2024-04-03 01:36:02       39 阅读
  3. 线常见使用

    2024-04-03 01:36:02       7 阅读
  4. 使用线常见的架构

    2024-04-03 01:36:02       26 阅读
  5. 线相关整理

    2024-04-03 01:36:02       22 阅读
  6. 线相关知识

    2024-04-03 01:36:02       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-03 01:36:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-03 01:36:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-03 01:36:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-03 01:36:02       20 阅读

热门阅读

  1. js根据开始和结束时间进行搜索

    2024-04-03 01:36:02       14 阅读
  2. 题目:学习使用auto定义变量的用法

    2024-04-03 01:36:02       17 阅读
  3. os模块篇(六)

    2024-04-03 01:36:02       13 阅读
  4. Python实现逻辑回归(Logistic Regression)

    2024-04-03 01:36:02       15 阅读
  5. 关于矩阵的摄动。

    2024-04-03 01:36:02       16 阅读