c语言中的多线程编程
   资源分享   1 评论   1811 浏览

c语言中的多线程编程

   资源分享   1 评论   1811 浏览
#include<stdio.h>

#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<NUM;i++)
    {
        printf("%s",m);
        fflush(stdout);
        sleep(1);
    }
}

执行结果:

hello,hello,hello,hello,hello,hello,world!world!world!world!world!world!

那么如果想同时执行两个对于print_msg函数的调用,就想建立两个新的进程一样,那该怎么办?怎么才能达到这种多线程效果呢?

以下两个函数都包含在头文件pthread.h中
我们可以使用函数pthread_create创建一个新的线程:

函数原型:

int pthread_create( pthread_t   *thread,   pthread_attr_t *attr,    void   *(*func),   void   *arg);

参数:

    thread     指向pthread_t类型变量的指针,  **typedef unsigned long int pthread_t, pthread_t用于声明线程ID**
      attr     指向pthread_attr_t类型变量的指针,或者为NULL
      func     指向新线程所运行函数的指针
       arg     传递给func的参数
    返回值0     成功返回
   errcode     错误

我们可以使用函数pthread_join等待某进程结束:

函数原型:

int pthread_join(pthread_t  thread, void **  retval);

参数:

    thread         所等待的进程
    retval         指向某存储线程返回值的变量

返回值:

    0              成功返回
    errorcode      错误
#include<stdio.h>
#include<pthread.h>
#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!\n");
   
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);  
}
void print_msg(void* m)
{
    char *cp=(char*)m;
    int i;
    for(i=0;i<NUM;i++)
    {
        printf("%s",m);
        fflush(stdout);
        sleep(1);
    }
}

运行结果:

hello,world!
hello,world!
hello,world!
hello,world!
hello,world!
hello,world!

C语言有一次拓展了我的视野,多线程的问题还有很多,像线程间的分工合作、使用互斥机制保证线程间数据的安全共享、使用条件变量同步线程间的数据传输、传递多个参数给线程等,若读者有兴趣,可自行深入。

线程的堆栈问题

线程就是个无产阶级,但无产阶级干活,总得有自己的劳动工具吧,这个劳动工具就是栈,线程有自己的栈,这个栈仍然是使用进程的地址空间,只是这块空间被线程标记为了栈。

每个线程都会有自己名义上私有的堆栈,之所以说是名义上的,是由于这些线程属于同一个进程,其他线程只要获取了你的私有堆栈上某些数据的指针,其他线程便可以自由访问你名义上的私有空间的数据变量,不过必须做好同步保护。而且一般不这样做,因为容易造成堆内内存管理混乱破坏线程栈空间等问题。

本文由 RawChen 发表, 最后编辑时间为:2020-07-25 09:45
如果你觉得我的文章不错,不妨鼓励我继续写作。

发表评论
选择表情
  1. 膜拜C语言大佬_(:з」∠)_

       Windows 10   Chrome 80
Top