ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Linux多线程编程

2020-12-04 12:04:08  阅读:142  来源: 互联网

标签:printf Linux int 编程 pid 线程 pthread tid 多线程


1.线程资源回收
(1)每个线程创建后,可以由主线程调用pthread_detach()函数来让它变为unjoinable状态或者每个线程开始的时候自己调用pthread_detach(pthread_self()),这样线程在退出的时候,会自动释放自己占用的系统资源,包括线程描述符和栈等资源。
(2)通过主线程调用**pthread_join()**函数,阻塞地等待线程结束,收到线程返回值,然后释放线程资源。
(3)涉及线程函数
pthread_create()
pthread_detach()
pthread_join()
pthread_self()
(4)代码示例:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

char* thread_func1(void* arg) {
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();
    printf("%s pid: %u, tid: %u (0x%x)\n", (char*)arg, (unsigned int)pid, (unsigned int)tid, 
        (unsigned int)tid);

    char* msg = "thread_fucn1";
    return msg;
}

void* thread_func2(void* arg) {
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();
    printf("%s pid: %u, tid: %u (0x%x)\n", (char*)arg, (unsigned int)pid, (unsigned int)tid, 
        (unsigned int)tid);

    char* msg = "thread_fucn2";
    while (1) {
        printf("%s running\n", msg);
        sleep(5);
    }

    return NULL;
}

int main(void) {
    pthread_t tid1;
    pthread_t tid2;
    char* ret = NULL;

    if (pthread_create(&tid1, NULL, (void*)thread_func1, "thread1") != 0) {
        printf("pthread_create tid1 error\n");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&tid2, NULL, (void*)thread_func2, "thread2") != 0) {
        printf("pthread_create tid2 error\n");
        exit(EXIT_FAILURE);
    }
    
    pthread_detach(tid2);

    pthread_join(tid1, (void*)&ret);
    printf("%s return\n", ret);

    sleep(5);
    pthread_cancel(tid2);

    printf("main thread end\n");
    return 0;
}

标签:printf,Linux,int,编程,pid,线程,pthread,tid,多线程
来源: https://blog.csdn.net/weixin_44250058/article/details/110632228

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有