IT狗工作室C语言C语言&嵌入式

第2篇 Linux多线程

2019-12-31  本文已影响0人  铁甲万能狗

前面的一篇,介绍了进程和线程的关系,以及创建了一个简单的单线程的程序。我们下面通过主线程中使用pthread_create系统调用创建一个或多个子线程。

int pthread_create(
    pthread_t *thread,                  //线程ID
    const pthread_attr_t *attr,  //线程属性
    void *(*start_routine) (void *),   //回调函数
    void *arg                                      //回调函数的参数
);
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void display_id(char* s){
      pid_t pid;
      pthread_t tid;
      
      pid=getpid();
      tid=pthread_self();
      printf("%s 进程: %u, 线程ID 0x%lx\n",s,pid,tid);
}


void *thread_func(void* args){
      display_id(args);
       return (void*)0;
}

int main(){
      pthread_t ntid;
      int err;
      err=pthread_create(&ntid,NULL,thread_func,"子线程");
      if(err!=0){
            printf("创建线程失败\n");
            return 0;
      }

      display_id("主线程:");
      sleep(3);
      return 0;
}
2019-12-31 10-53-50屏幕截图.png

小结

本篇介绍了如何通过pthread_create系统调用,在主线程中创建出一个子线程。并且分别打印各个线程中的进程ID和线程ID,我们知道,一个进程中的多个线程共享同一个进程的资源

上一篇 下一篇

猜你喜欢

热点阅读