zoukankan      html  css  js  c++  java
  • 多线程同步

    概念:多个线程按照规定的顺序来执行,即为线程同步

    扫地5次后拖地模型

    #include<pthread.h>
    #include<stdio.h>

    pthread_mutex_t mut;
    pthread_t thread[2];
    int number=0;

    void studentA()
    {
    int i;

    for(i=0;i<5;i++)
    {
    //扫地1次
    pthread_mutex_lock(&mut); //使用前保护起来
    number++;
    if(number>=5)
    printf("studentA has finished his work ");

    //休息1秒
    pthread_mutex_unlock(&mut); //使用后解开
    sleep(1);

    }

    //扫地5次,退出
    pthread_exit(NULL);
    }


    void studentB()
    {

    while(1)

    {
    //判断A是否扫地5次了
    pthread_mutex_lock(&mut); //使用前保护起来

    if(number>=5)
    {
    //拖地
    number=0;
    pthread_mutex_unlock(&mut); //使用后解开
    printf("studentB has finished his work ");
    break;
    }

    else
    {
    //睡2秒
    sleep(2);
    }
    }
    //退出
    pthread_exit(NULL);
    }

    int main()
    {
    //初始化互斥锁
    pthread_mutex_init(&mut,NULL);

    //创建A同学线程程
    pthread_create(&thread[0], NULL,studentA,NULL);

    //创建B同学线程
    pthread_create(&thread[1], NULL,studentB,NULL);

    //等待A同学线程程结束
    pthread_join( thread[0], NULL);

    //等待B同学线程程结束
    pthread_join( thread[1], NULL);

    }

  • 相关阅读:
    Github国内mirror加速
    通过node-inspector或VSCode调试服务器上代码
    node nvm 常见命令
    HBuilderX 修改默认的终端
    LLVM 工具使用
    LLVM 获取Value Type
    LLVM Constant Value to c++ value
    Bison 命名位置
    llvm block
    vscode use cl.exe build C/C++
  • 原文地址:https://www.cnblogs.com/1932238825qq/p/7373166.html
Copyright © 2011-2022 走看看