linux如何让一个线程执行
时间: 2024-05-04 15:20:22 浏览: 10
在Linux中,使用pthread库来创建和管理线程。下面是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
printf("This is a new thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_func, NULL);
if (ret != 0) {
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
printf("Created a new thread with ID: %ld\n", thread);
pthread_join(thread, NULL);
printf("Thread %ld has finished\n", thread);
return 0;
}
```
在上面的例子中,我们通过调用pthread_create函数创建了一个新线程,该函数需要传入4个参数:第一个参数为指向线程ID的指针,第二个参数为线程属性(可以为NULL),第三个参数为线程函数,最后一个参数为传递给线程函数的参数(可以为NULL)。
在示例中,我们创建了一个线程并调用了thread_func函数来执行线程。在这个函数中,我们简单地打印一条消息,然后返回NULL。在主函数中,我们使用pthread_join函数等待线程结束并打印一条相应的消息。