阅读量:123
pthread_t 是 POSIX 线程库中表示线程的数据类型
- 包含头文件:在你的源代码文件中,需要包含
头文件。
#include
- 定义线程函数:创建一个线程函数,该函数将在新线程中运行。线程函数应该接受一个
void *类型的参数,并返回一个void *类型的值。
void *thread_function(void *arg) {
// 在这里编写你的线程执行代码
return NULL;
}
- 创建线程变量:定义一个
pthread_t类型的变量,用于存储线程的 ID。
pthread_t thread_id;
- 创建线程:使用
pthread_create()函数创建一个新线程。该函数需要三个参数:指向线程 ID 的指针、线程属性(通常为NULL)和线程函数的地址。
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
printf("Error creating thread: %d\n", result);
exit(1);
}
- 等待线程结束(可选):如果你需要等待线程完成其任务,可以使用
pthread_join()函数。该函数需要两个参数:线程 ID 和一个指向void *类型的指针,用于存储线程函数的返回值。
void *return_value;
int result = pthread_join(thread_id, &return_value);
if (result != 0) {
printf("Error joining thread: %d\n", result);
exit(1);
}
- 使用互斥锁或其他同步原语来实现并发控制。例如,使用
pthread_mutex_t类型的互斥锁来保护共享资源。
#include
#include
#include
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_counter = 0;
void *thread_function(void *arg) {
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&mutex);
shared_counter++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
const int NUM_THREADS = 10;
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM class="hljs-type">int result = pthread_create(&threads[i], NULL, thread_function, NULL);
if (result != 0) {
printf("Error creating thread: %d\n", result);
exit(1);
}
}
for (int i = 0; i < NUM class="hljs-type">void *return_value;
int result = pthread_join(threads[i], &return_value);
if (result != 0) {
printf("Error joining thread: %d\n", result);
exit(1);
}
}
printf("Shared counter: %d\n", shared_counter);
return 0;
}
这个示例展示了如何使用 pthread_t、互斥锁和其他 POSIX 线程函数来实现并发控制。注意,这个示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和资源管理。