• 多线程常识相关


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

  • 相关阅读:
    【校招VIP】前端操作系统之存储管理加密
    webpack学习记录
    OpenGL、Open3D常用代码片段(C++, python)【更新中】
    计算机网络-第4章 网络层
    关于主表和子表数据的保存
    微信小程序 自定义tab不煽动
    9.基于粤嵌gec6818开发板小游戏2048的算法实现
    多线程下的时间处理
    JAVA--企业级分层开发模式
    QIBOX1-014-栏目的调用2
  • 原文地址:https://blog.csdn.net/weixin_44322824/article/details/137277201