linux pthread_attr_t 结构体给出实现例子
下面是一个简单的例子,展示了如何使用pthread_attr_t结构体和相关函数来创建和设置线程属性:
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
printf("Hello from the new thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
pthread_attr_t attr;
// 初始化线程属性
pthread_attr_init(&attr);
// 创建线程
pthread_create(&thread, &attr, thread_func, NULL);
// 等待线程结束
pthread_join(thread, NULL);
// 销毁线程属性
pthread_attr_destroy(&attr);
return 0;
}
在这个例子中,我们首先使用pthread_attr_init函数初始化pthread_attr_t结构体。然后,使用pthread_create函数创建一个新的线程,并传入线程属性对象attr、线程函数thread_func和线程函数的参数NULL。接着,使用pthread_join函数等待新线程结束。最后,使用pthread_attr_destroy函数销毁线程属性对象。
注意:pthread_attr_t结构体提供了许多其他函数来设置线程属性,如设置线程栈大小、设置线程分离状态等。你可以根据自己的需求使用这些函数来设置线程属性
原文地址: https://www.cveoy.top/t/topic/iQa0 著作权归作者所有。请勿转载和采集!