【C语言】多线程

简介: 【C语言】多线程

多线程

  线程是轻量级的线程(LWP:light weight process)

  线程是最小执行单位,进程是最小分配资源单位。一个进程可以有多个线程,一个进程可以理解为只有一个线程的进程。

  每个线程都有自己独立的pcb,它们有独立的线程id和线程号,线程id是程序员使用,线程号是系统使用,同一个进程的线程,它们的进程id是一样的,共享进程空间。

  可以使用命令 ps -Lf pid 来查看线程号。

  不管是fork创建子进程还是pthreadcreate 创建线程,底层实现都是调用同一个内核函数clone。区别就是复制原始进程的地址空间,那么就会创建一个子进程。如果共享原始进程的地址空间,那么就会创建一个线程。系统内核是不区分进程和线程的,因为它们都有自己独立的pcb,只有在用户层面的概念上区分。因此可以看出线程相关的 pthread 系列函数是库函数而不是系统调用。

一、线程创建和回收

循环创建线程

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

void *threadMethod(void *num)
{
   
    printf("this thread num is [%d], pid is [%d],tid is [%ld]\n", *(int *)num, getpid(), pthread_self());
    sleep(30);
}

int main()
{
   
    int arr[5];
    pthread_t thread[5];
    int i;
    int ret;
    for (i = 0; i < 5; i++)
    {
   
        arr[i] = i;
        ret = pthread_create(&thread[i], NULL, threadMethod, &arr[i]);
        if (ret != 0)
        {
   
            printf("pthread_create error, [%s]\n", strerror(ret));
            return -1;
        }
    }
    printf("main thread, pid is [%d], tid is [%ld]\n", getpid(), pthread_self());
    sleep(30);
    return 0;
}

多线程使用pthread_exit退出线程,并用pthread_join接收退出状态

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

int * nums;

void* thread_function(void* arg) {
   
    // 线程执行的代码
    int thread_id = *(int *)arg;
    nums[thread_id] = thread_id + 5;
    printf("Thread %d exiting,pid is [%d],tid is [%ld]\n", thread_id,getpid(),pthread_self());
    pthread_exit(&nums[thread_id]);
}

int main() {
   
    nums = (int *)malloc(sizeof(int)*5);
    pthread_t threads[5];
    int indexes[5] = {
   1, 2, 3, 4, 5}; // 线程索引,用于打印

    for(int i = 0; i < 5; i++) {
   
        int ret = pthread_create(&threads[i], NULL, thread_function, &indexes[i]);
        if (ret) {
   
            printf("Thread creation error: %d\n", ret);
            return -1;
        }
    }

    void* exit_status;
    for(int i = 0; i < 5; i++) {
   
        int ret = pthread_join(threads[i], &exit_status);
        if (ret) {
   
            printf("Thread join error: %d\n", ret);
            return -1;
        }
        printf("Thread %d exited with status: %d\n", i, *(int *)exit_status);
    }

    return 0;
}
//输出
Thread 1 exiting,pid is [1913],tid is [140703346046720]
Thread 2 exiting,pid is [1913],tid is [140703337654016]
Thread 3 exiting,pid is [1913],tid is [140703329261312]
Thread 4 exiting,pid is [1913],tid is [140703320868608]
Thread 5 exiting,pid is [1913],tid is [140703312475904]
Thread 0 exited with status: 6
Thread 1 exited with status: 7
Thread 2 exited with status: 8
Thread 3 exited with status: 9
Thread 4 exited with status: 10

二、线程属性

pthread_create函数中的线程属性参数设置步骤

//1.定义线程属性变量
pthread_attr_t  attr;
//2.线程属性初始化,成功返回0,失败返回失败编号
int pthread_attr_init (pthread_attr_t* attr);
//3.线程属性变量添加分离属性,其中detachstate可以设置为
//PTHREAD_CREATE_DETACHED(分离)和PTHREAD_CREATE_JOINABLE(非分离)
//成功返回0,失败返回失败编号
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
//4.创建线程后释放变量,成功返回0,失败返回失败编号
int pthread_attr_destroy(pthread_attr_t *attr);

三、线程分离

使用pthread_detach函数实现线程分离,线程的退出后不需要手动去回收资源,设置线程分离有两种方法,一个是使用pthread_detach函数,另一个是在pthread_create函数中添加分离属性。

方式一:使用pthread_detach函数实现线程分离

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

void *threadMethod(void *num)
{
   
    printf("this thread pid is [%d],tid is [%ld]\n", getpid(), pthread_self());
}

int main()
{
   
    pthread_t thread;
    int ret = pthread_create(&thread, NULL, threadMethod, NULL);
    if (ret != 0)
    {
   
        printf("pthread_create error, [%s]\n", strerror(ret));
        return -1;
    }
    ret = pthread_detach(thread);
    if (ret != 0)
    {
   
        printf("pthread_detach error, [%s]\n", strerror(ret));
        return -1;
    }
    printf("main thread, pid is [%d], tid is [%ld]\n", getpid(), pthread_self());
    sleep(1);
    return 0;
}

方式二:pthread_create函数中添加分离属性

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

void *threadMethod(void *num)
{
   
    printf("this thread pid is [%d],tid is [%ld]\n", getpid(), pthread_self());
}

int main()
{
   
    int ret;
    pthread_attr_t  attr;
    ret = pthread_attr_init(&attr);
    if (ret != 0)
    {
   
        printf("pthread_attr_init error, [%s]\n", strerror(ret));
        return -1;
    }
    ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    if (ret != 0)
    {
   
        printf("pthread_attr_setdetachstate error, [%s]\n", strerror(ret));
        return -1;
    }

    pthread_t thread;
    ret = pthread_create(&thread, &attr, threadMethod, NULL);
    pthread_attr_destroy(&attr);
    if (ret != 0)
    {
   
        printf("pthread_create error, [%s]\n", strerror(ret));
        return -1;
    }

    printf("main thread, pid is [%d], tid is [%ld]\n", getpid(), pthread_self());
    sleep(1);
    return 0;
}
//输出
main thread, pid is [2063], tid is [139936574068480]
this thread pid is [2063],tid is [139936565679872]
目录
相关文章
|
27天前
|
安全 Java C语言
C语言线程解池解读和实现01
C语言线程解池解读和实现01
|
8天前
|
网络协议 C语言
C语言 网络编程(十四)并发的TCP服务端-以线程完成功能
这段代码实现了一个基于TCP协议的多线程服务器和客户端程序,服务器端通过为每个客户端创建独立的线程来处理并发请求,解决了粘包问题并支持不定长数据传输。服务器监听在IP地址`172.17.140.183`的`8080`端口上,接收客户端发来的数据,并将接收到的消息添加“-回传”后返回给客户端。客户端则可以循环输入并发送数据,同时接收服务器回传的信息。当输入“exit”时,客户端会结束与服务器的通信并关闭连接。
|
8天前
|
存储 Ubuntu Linux
C语言 多线程编程(1) 初识线程和条件变量
本文档详细介绍了多线程的概念、相关命令及线程的操作方法。首先解释了线程的定义及其与进程的关系,接着对比了线程与进程的区别。随后介绍了如何在 Linux 系统中使用 `pidstat`、`top` 和 `ps` 命令查看线程信息。文档还探讨了多进程和多线程模式各自的优缺点及适用场景,并详细讲解了如何使用 POSIX 线程库创建、退出、等待和取消线程。此外,还介绍了线程分离的概念和方法,并提供了多个示例代码帮助理解。最后,深入探讨了线程间的通讯机制、互斥锁和条件变量的使用,通过具体示例展示了如何实现生产者与消费者的同步模型。
|
8天前
|
C语言
C语言 网络编程(九)并发的UDP服务端 以线程完成功能
这是一个基于UDP协议的客户端和服务端程序,其中服务端采用多线程并发处理客户端请求。客户端通过UDP向服务端发送登录请求,并根据登录结果与服务端的新子线程进行后续交互。服务端在主线程中接收客户端请求并创建新线程处理登录验证及后续通信,子线程创建新的套接字并与客户端进行数据交换。该程序展示了如何利用线程和UDP实现简单的并发服务器架构。
|
23天前
|
C语言
【C语言】线程同步
【C语言】线程同步
27 3
|
23天前
|
C语言
【C语言】多线程服务器
【C语言】多线程服务器
14 0
|
2月前
|
调度 C语言
深入浅出:C语言线程以及线程锁
线程锁的基本思想是,只有一个线程能持有锁,其他试图获取锁的线程将被阻塞,直到锁被释放。这样,锁就确保了在任何时刻,只有一个线程能够访问临界区(即需要保护的代码段或数据),从而保证了数据的完整性和一致性。 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。一个进程可以包含一个或多个线程,而每个线程都有自己的指令指针和寄存器状态,它们共享进程的资源,如内存空间、文件句柄和网络连接等。 线程锁的概念
|
3月前
|
存储 Linux C语言
c++进阶篇——初窥多线程(二) 基于C语言实现的多线程编写
本文介绍了C++中使用C语言的pthread库实现多线程编程。`pthread_create`用于创建新线程,`pthread_self`返回当前线程ID。示例展示了如何创建线程并打印线程ID,强调了线程同步的重要性,如使用`sleep`防止主线程提前结束导致子线程未执行完。`pthread_exit`用于线程退出,`pthread_join`用来等待并回收子线程,`pthread_detach`则分离线程。文中还提到了线程取消功能,通过`pthread_cancel`实现。这些基本操作是理解和使用C/C++多线程的关键。
|
4月前
|
安全 Linux 编译器
从C语言到C++_40(多线程相关)C++线程接口+线程安全问题加锁(shared_ptr+STL+单例)(下)
从C语言到C++_40(多线程相关)C++线程接口+线程安全问题加锁(shared_ptr+STL+单例)
34 0
|
4月前
|
安全 C语言 C++
从C语言到C++_40(多线程相关)C++线程接口+线程安全问题加锁(shared_ptr+STL+单例)(中)
从C语言到C++_40(多线程相关)C++线程接口+线程安全问题加锁(shared_ptr+STL+单例)
41 0