在Linux系统中,创建线程通常使用POSIX线程接口,即pthread。pthread提供了一组函数用于创建和管理线程。以下是创建线程的基本概念和相关函数:
pthread_create
:用于创建新线程。pthread_create
:用于创建新线程。thread
:指向新创建线程的标识符的指针。attr
:指向线程属性的指针,如果为NULL,则使用默认属性。start_routine
:线程开始执行的函数指针。arg
:传递给start_routine
函数的参数。#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* print_hello(void* data) {
printf("Hello from thread %ld\n", pthread_self());
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int rc;
long t;
for(t=0;t<5;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void*)t);
if (rc){
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0;t<5;t++){
pthread_join(threads[t], NULL);
}
pthread_exit(NULL);
}
pthread_create
返回非零值,表示线程创建失败。可以通过检查返回值并参考man page来确定失败原因。通过以上信息,你应该能够理解Linux中创建线程的基本概念、相关函数、优势、应用场景以及常见问题及其解决方法。
领取专属 10元无门槛券
手把手带您无忧上云