• 多线程常识相关


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

    #include 
    #include 
    #include 
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    这里运行的结果是:
    所有票被抢完以后,才依次输出
    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;
    这几句话会交错掺杂在抢票结果过程中。抢票未结束的时候主线程就已经退出了。因为进程结束,所以所有线程都杀死。

  • 相关阅读:
    Java模糊查询批量删除Redis的Key实现
    SQL中的索引
    【GD32F427开发板试用】FreeRTOS移植工程
    【C++】不能两次杀死同一条鱼 - 浅述shared_ptr智能指针的使用方法
    Dart(12)-异常
    plink如何更新表型数据
    2024年MathorCup数学建模思路D题思路分享
    Spring IOC - Bean的生命周期之实例化
    车载网络安全指南 概述(一)
    Servlet入门接口、类和配置学习
  • 原文地址:https://blog.csdn.net/weixin_44322824/article/details/137277201