threads6 线程脱离属性detach

本文通过一个具体的C语言示例程序,详细介绍了如何使用POSIX线程库(pthread)来创建和管理线程,包括线程的创建、设置属性、同步与等待等关键操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//beginging linux programming ch12
[root@localhost ch12]# cat thread5.c 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function(void *arg);

char message[] = "Hello World";
int thread_finished = 0;
    int res;
int main() {
	int res;
	pthread_t a_thread;
	void *thread_result;
	pthread_attr_t thread_attr;

	res = pthread_attr_init(&thread_attr);
	if (res != 0) {
	perror("Attribute creation failed");
	exit(EXIT_FAILURE);
	}
	res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
	if (res != 0) {
	perror("Setting detached attribute failed");
	exit(EXIT_FAILURE);
	}


	res = pthread_create(&a_thread,NULL, thread_function, (void *)message);
	//&thread_attr

	if (res != 0) {
	perror("Thread creation failed");
	exit(EXIT_FAILURE);
	}


	(void)pthread_attr_destroy(&thread_attr);
	 res = pthread_join(a_thread, &thread_result);
	printf("Other thread finished, bye!\n");
	// pthread_exit(NULL);
	exit(0);
}

void *thread_function(void *arg) {

	printf("thread_function is running. Argument was %s\n", (char *)arg);
	sleep(1);
	printf("Second thread setting finished flag, and exiting now\n");
	thread_finished = 1;
	pthread_exit(NULL);
}
[root@localhost ch12]# make
cc -D_REENTRANT  -lpthread  thread5.c   -o thread5
[root@localhost ch12]# ./thread5
thread_function is running. Argument was Hello World
Second thread setting finished flag, and exiting now
Other thread finished, bye!
[root@localhost ch12]# 
modify line31 shown below
	res = pthread_create(&a_thread,&thread_attr, thread_function, (void *)message);
then
[root@localhost ch12]# ./thread5
Other thread finished, bye!
[root@localhost ch12]# 
可见
用NULL创建的子线程,主线程可用pthread_join使自己等待子线程结束(主线程阻塞在pthread_join的位置)
而用DETACH创建的子线程,主线程用pthread_join也不会使自己阻塞,而是一直执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值