zoukankan      html  css  js  c++  java
  • C语言中的多线程编程

    很久很久以前,我对C语言的了解并不是很多,我最早听说多线程编程是用Java,其实C语言也有多线程编程,而且更为简单、方便、强大。下面就让我们简单领略一下Unix C语言环境下的多线程编程吧!
    下面先看一个简单的单线程程序:
    /* 06.3.6
       Sghello.c
       Hello,world -- Single Thread
    */
    #include
    #define NUM 6
    int main()
    {
        void print_msg(char*);
        print_msg("hello,");
        print_msg("world!");
    }
    void print_msg(char* m)
    {
        int i;
        for(i=0;i
        {
            printf("%s",m);
            fflush(stdout);
            sleep(1);
        }
    }
    下图反映了程序的执行流程:
    
    执行结果:
    $ ./sghello.exe
    hello,hello,hello,hello,hello,hello,world!world!world!world!world!world!
     
    那么如果想同时执行两个对于print_msg函数的调用,就想使用fork建立两个新的进程一样,那该怎么办?这种思想清楚的体现在下图:
    
    那么怎么才能达到这种效果呢?
    我们可以使用函数pthread_create创建一个新的线程。
    函数原型:
    int pthread_create(pthread_t         *thread,
    pthread_attr_t *attr,
    void              *(*func)(void*),
    void              *arg);
    参数:                     thread     指向pthread_t类型变量的指针
                                 attr         指向pthread_attr_t类型变量的指针,或者为NULL
                                 func        指向新线程所运行函数的指针
                                 arg          传递给func的参数
    返回值                        0            成功返回
                                      errcode    错误
    我们可以使用函数pthread_join等待某进程结束。
    函数原型:int pthread_join(pthread_t thread,void ** retval);
    参数:     thread         所等待的进程
                  retval          指向某存储线程返回值的变量
    返回值: 0                成功返回
                 errorcode    错误
    以上两个函数都包含在头文件pthread.h中。
           下面请看多线程版的Hello,world!
    /* 06.3.6
       Mhello1.c
       Hello,world -- Multile Thread
    */
    #include
    #include
    #define NUM 6
    int main()
    {
        void print_msg(void*);
        
        pthread_t t1,t2;
        pthread_create(&t1,NULL,print_msg,(void *)"hello,");
        pthread_create(&t2,NULL,print_msg,(void *)"world!
    ");
        
        pthread_join(t1,NULL);
        pthread_join(t2,NULL);   
    }
    void print_msg(void* m)
    {
        char *cp=(char*)m;
        int i;
        for(i=0;i
        {
            printf("%s",m);
            fflush(stdout);
            sleep(1);
        }
    }
    运行结果:
    $ gcc mhello1.c
    -o mhello1.exe $ ./mhello1.exe hello,world! hello,world! hello,world! hello,world! hello,world! hello,world! C语言有一次拓展了我的视野,多线程的问题还有很多,像线程间的分工合作、使用互斥机制保证线程间数据的安全共享、使用条件变量同步线程间的数据传输、传递多个参数给线程等,若读者有兴趣,可自行深入。 推荐《Understanding Unix/Linux Programming》
  • 相关阅读:
    wqy的ACM赛G朱柏庐
    可持久化数据结构
    LibreOJ#2362蚯蚓
    LibreOJ#2359天天爱跑步
    「Luogu2221」[HAOI2012]高速公路
    「Luogu4158」[SCOI2009]粉刷匠
    「Luogu4317」花神的数论题
    WC2019 游记
    最大权闭合子图模型
    「Luogu2762」太空飞行计划问题
  • 原文地址:https://www.cnblogs.com/aimqqroad-13/p/5666136.html
Copyright © 2011-2022 走看看