C++创建线程


前言

线程是轻量级的进程(LWP:light weight process),在Linux环境下线程的本质仍是进程。在计算机上运行的程序是一组指令及指令参数的组合,指令按照既定的逻辑控制计算机运行。操作系统会以进程为单位,分配系统资源,可以这样理解,进程是资源分配的最小单位,线程是操作系统调度执行的最小单位。


一、知识点

1、线程ID类型为pthread_t,它是一个无符号长整形数,如果想查看当前线程的线程ID,可以调用这个函数:

pthread_t pthread_self(void);	// 返回当前线程的线程ID

2、线程创建函数,需要给每一个创建出的线程指定一个任务函数。

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);
// Compile and link with -pthread, 线程库的名字叫pthread, 全名: libpthread.so libptread.a

二、代码

代码如下(示例):

// pthread_create.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

// 子线程的处理代码
void *working(void *arg)
{
    
    
    int i;
    for (i = 0; i < 5; ++i)
    {
    
    
        printf("child_thread :i = %d\n", i);
    }
    printf("child_thread ID: %ld\n", pthread_self());
    return NULL;
}

int main()
{
    
    
    // 1. 创建一个子线程
    pthread_t tid;
    pthread_create(&tid, NULL, working, NULL);
    // 2. 子线程不会执行下边的代码, 主线程执行
    int i;
    for (i = 0; i < 5; ++i)
    {
    
    
        printf("father_thread :i = %d\n", i);
    }
    printf("father_thread ID: %ld\n", pthread_self());
    // 休息, 休息一会儿...
    sleep(3);
    return 0;
}

三、编译运行

Linux操作系统下:

gcc pthread_create.c -lpthread -o run
./run

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/a_13572035650/article/details/132007190
今日推荐