多线程

Posted on 2023-02-23 13:12  lyc2002  阅读(13)  评论(0编辑  收藏  举报

介绍

获得线程号

#include <pthread.h>

pthread_t pthread_self(void);

功能:得到线程 id

参数:无

返回值:调用此函数的线程 id

创建线程

#include <pthread.h>

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

功能:创建线程

参数:

  • thread:传出参数,线程创建成功会将线程 id 写入该指针指向的内存中
  • attr:线程的属性,一般使用默认属性,传入 NULL
  • start_routine:创建的子线程的工作函数
  • arg:工作函数的参数

返回值:

  • 成功返回 0
  • 失败返回对应错误号

线程退出

#include <pthread.h>

void pthread_exit(void *retval);

功能:线程退出,并且不会影响到其他线程运行,不管是在子线程或主线程都可以使用

参数:

  • retval:线程退出时携带的数据,当前子线程的主线程会得到。不需要的话传入 NULL

返回值:无

回收线程

#include <pthread.h>

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

功能:阻塞函数,回收子线程资源

参数:

  • thread:要被回收的子线程 id
  • retval:二级指针,指向一级指针的地址,传出参数,储存了 pthread_exit 传递的数据,可指定为 NULL

返回值:

  • 成功返回 0
  • 失败返回错误号

分离线程

#include <pthread.h>

int pthread_detach(pthread_t thread);

功能:子线程可以和主线程分离,当子线程退出时,其占用的内核资源被系统的其他进程接管并回收

参数:

  • thread:要分离的线程 id

返回值:

  • 成功返回 0
  • 失败返回错误号

简单使用

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

void * work(void *arg)
{
    printf("我是子线程 id:%ld\n", pthread_self());
    for (int i = 0; i < 5; i++) {
        printf("child : %d\n", i);
	}
    
    pthread_exit(NULL);
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, work, NULL);
    
    printf("我是主线程 id:%ld,我创建子线程 id:%ld\n", pthread_self(), tid);
    
    for (int i = 0; i < 10; i++) {
        printf("parent : %d\n", i);
    }
    
    pthread_exit(NULL);
    
    // return 0;
}

注意事项

  • 编译选项要加上 -lpthread