C++ creates threads


foreword

A thread is a lightweight process (LWP: light weight process), and the essence of a thread in a Linux environment is still a process. The program running on the computer is a combination of a set of instructions and instruction parameters, and the instructions control the operation of the computer according to the established logic. The operating system allocates system resources in units of processes. It can be understood that a process is the smallest unit of resource allocation, and a thread is the smallest unit of operating system scheduling and execution.


1. Knowledge points

1. The thread ID type is pthread_t, which is an unsigned long integer. If you want to check the thread ID of the current thread, you can call this function:

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

2. The thread creation function needs to specify a task function for each created thread.

#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

Two, the code

The code is as follows (example):

// 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;
}

3. Compile and run

Under the Linux operating system:

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

insert image description here

Guess you like

Origin blog.csdn.net/a_13572035650/article/details/132007190