线程的创建和撤销
时间: 2024-02-12 08:03:56 浏览: 95
在C语言中,可以使用POSIX线程库(pthread)来创建和撤销线程。线程的创建和撤销分别使用pthread_create和pthread_cancel函数。
1. 线程的创建:
pthread_create函数用于创建一个新线程,它的原型如下:
```
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
```
其中,参数thread是指向pthread_t类型的指针,用于存储新线程的标识符;参数attr是指向pthread_attr_t类型的指针,用于指定线程的属性,一般使用默认值即可;参数start_routine是指向线程启动函数的指针,它是新线程的入口点;参数arg是传递给start_routine函数的参数。
创建线程的示例代码如下:
```
#include <pthread.h>
#include <stdio.h>
void *my_thread(void *arg) {
printf("Hello, world!\n");
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, my_thread, NULL);
pthread_join(tid, NULL);
return 0;
}
```
在上面的示例中,创建了一个新的线程并执行my_thread函数,在my_thread函数中输出了一条消息。主线程使用pthread_join函数等待新线程结束。
2. 线程的撤销:
pthread_cancel函数用于取消一个线程的执行,它的原型如下:
```
int pthread_cancel(pthread_t thread);
```
其中,参数thread是要被取消的线程的标识符。
线程的撤销示例代码如下:
```
#include <pthread.h>
#include <stdio.h>
void *my_thread(void *arg) {
while (1) {
printf("Hello, world!\n");
sleep(1);
}
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, my_thread, NULL);
sleep(5);
pthread_cancel(tid);
pthread_join(tid, NULL);
return 0;
}
```
在上面的示例中,创建了一个新的线程并执行my_thread函数,在my_thread函数中输出一条消息并等待一秒钟。主线程等待5秒钟后,使用pthread_cancel函数取消新线程的执行。主线程使用pthread_join函数等待新线程结束。
阅读全文
相关推荐
















