编写测试脚本测试pthread_key_create
时间: 2023-07-05 19:04:48 浏览: 65
好的,以下是一个简单的测试脚本示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_func(void* arg) {
pthread_key_t key;
// 创建一个线程特定数据键
if (pthread_key_create(&key, NULL) != 0) {
fprintf(stderr, "pthread_key_create failed\n");
exit(EXIT_FAILURE);
}
// 设置线程特定数据
int* data = (int*) malloc(sizeof(int));
*data = 42;
if (pthread_setspecific(key, data) != 0) {
fprintf(stderr, "pthread_setspecific failed\n");
exit(EXIT_FAILURE);
}
// 获取线程特定数据
int* retrieved_data = (int*) pthread_getspecific(key);
if (retrieved_data == NULL) {
fprintf(stderr, "pthread_getspecific failed\n");
exit(EXIT_FAILURE);
}
printf("Thread-specific data: %d\n", *retrieved_data);
// 释放线程特定数据键
free(data);
if (pthread_key_delete(key) != 0) {
fprintf(stderr, "pthread_key_delete failed\n");
exit(EXIT_FAILURE);
}
return NULL;
}
int main() {
pthread_t thread;
// 创建一个线程并启动
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
fprintf(stderr, "pthread_create failed\n");
exit(EXIT_FAILURE);
}
// 等待线程结束
if (pthread_join(thread, NULL) != 0) {
fprintf(stderr, "pthread_join failed\n");
exit(EXIT_FAILURE);
}
return 0;
}
```
该脚本创建一个线程特定数据键,然后在新线程中设置并获取该键的值。最后,它删除该键并等待线程结束。运行该脚本应输出以下内容:
```
Thread-specific data: 42
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)