zoukankan      html  css  js  c++  java
  • Linux 多线程编程 实例 1

    子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。

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

    static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

    static void *thread_func(void *arg)
    {
    //sleep(10);
    int j=3;
    while(j--)
    {

    pthread_mutex_lock(&mtx);
    pthread_cond_wait(&cond,&mtx);
    //pthread
    printf("10 times complete. ");
    //pthread
    pthread_mutex_unlock(&mtx);
    }
    }


    int main(void *arg)
    {
    pthread_t tid;
    pthread_create(&tid,NULL,thread_func,NULL);
    //sleep(5);
    int i=50;
    while(i--)
    {
    sleep(2);
    pthread_mutex_lock(&mtx);
    printf("100 times complete!. ");
    pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mtx);
    }
    //pthread_join(tid,NULL);
    //pthread_cancel(tid);
    pthread_join(tid,NULL);
    }

  • 相关阅读:
    Redis涉及的概念
    Redis高级教程
    Redis基础入门
    Java多线程面试题
    Java集合面试题
    Java集合基础
    Java基础面试题总结
    Zookeeper Basics
    GitLab基础入门
    阿里云ECS服务器Docker安装Tomcat过程记录
  • 原文地址:https://www.cnblogs.com/harlanc/p/5155519.html
Copyright © 2011-2022 走看看