Linux线程的基本操作主要包括以下几个方面:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
thread
:指向线程标识符的指针。attr
:线程属性,若为NULL则使用默认属性。start_routine
:线程启动函数指针。arg
:传递给线程启动函数的参数。void pthread_exit(void *retval);
retval
:线程退出状态,可以被其他线程通过pthread_join
获取。int pthread_join(pthread_t thread, void **retval);
thread
:要等待的线程标识符。retval
:存储线程退出状态的指针。int pthread_detach(pthread_t thread);
pthread_mutex_init
、pthread_mutex_lock
、pthread_mutex_unlock
和pthread_mutex_destroy
。pthread_cond_init
、pthread_cond_wait
、pthread_cond_signal
和pthread_cond_broadcast
。pthread_attr_t
结构体设置线程的各种属性,如栈大小、分离状态等。以下是一个简单的创建和等待线程的示例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* thread_func(void* arg) {
printf("Hello from thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread_id;
int ret;
ret = pthread_create(&thread_id, NULL, thread_func, NULL);
if (ret) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
printf("Hello from main!\n");
ret = pthread_join(thread_id, NULL);
if (ret) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
return 0;
}
通过以上内容,你可以掌握Linux线程的基本操作及相关概念。如有更具体的问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云