在Linux系统中,等待多个线程结束通常涉及到多线程编程中的同步机制。这里主要介绍几种常见的方法来实现这一目标:
线程(Thread):操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。
同步(Synchronization):在多线程编程中,同步是指协调不同线程之间的执行顺序,以确保它们能够正确地共享资源。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
pthread_mutex_t mutex;
pthread_cond_t cond;
int ready = 0;
void* thread_func(void* arg) {
int id = *(int*)arg;
pthread_mutex_lock(&mutex);
while (!ready) {
pthread_cond_wait(&cond, &mutex);
}
printf("Thread %d is running.\n", id);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
for (int i = 0; i < NUM_THREADS; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]);
}
// 主线程准备就绪,唤醒所有等待的线程
pthread_mutex_lock(&mutex);
ready = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
问题:线程间同步失败,导致数据不一致或死锁。
原因:
解决方法:
pthread_cond_wait
时,总是在循环中检查条件,以防止虚假唤醒。通过合理使用同步机制,可以有效地管理多个线程的执行流程,确保程序的正确性和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云