第2篇 Linux多线程

作者: 铁甲万能狗 | 来源:发表于2019-12-31 21:06 被阅读0次

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

int pthread_create(
    pthread_t *thread,                  //线程ID
    const pthread_attr_t *attr,  //线程属性
    void *(*start_routine) (void *),   //回调函数
    void *arg                                      //回调函数的参数
);
  • 线程ID:线程的唯一标识符,新创建的线程会将将id填充到thread指针的内存
  • 线程属性:调度策略/继承/分离(这里暂时不用理会,调用时候,传入参数NULL表示会使用默认的属性)
  • 回调函数的指针:当前线程栈通过传入函数指针调用被调用函数的主体
  • 回调函数的参数,由于该系统调用本身只有一个参数,因此如果需要向回调参数传递多个参数的话,请使用struct封装多个参数。
#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,我们知道,一个进程中的多个线程共享同一个进程的资源

相关文章

  • 多线程编程

    多线程编程之Linux环境下的多线程(一)多线程编程之Linux环境下的多线程(二)多线程编程之Linux环境下的...

  • Linux多线程编程实例解析

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • Linux C语言多线程编程实例解析

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • Linux多线程编程实例解析

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • Linux之多线程编程实例

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • Linux多线程实例解析

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • Linux多线程编程实例解析

    Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件...

  • 多线程编程

    参考:C++ 并发编程 线程 windsows多线程 new thread(...) linux 多线程: pth...

  • 5.多线程注意事项

    分析工具:1. ThreadSanitizer2. valgrind多线程注意事项:1. linux的多线程编程的...

  • Linux 线程CPU占用率过高定位分析

    在Linux开发中经常会与多线程打交道,所以多线程开发与调试就很重要 下边说下Linux调试过程中CPU占用率过高...

网友评论

    本文标题:第2篇 Linux多线程

    本文链接:https://www.haomeiwen.com/subject/dpcboctx.html