线程同步是指多个线程在同时访问共享资源时,为了避免数据不一致或者竞争条件等问题,需要进行协调和同步的机制。常见的线程同步机制有互斥锁、条件变量、信号量等。
以下是一个使用互斥锁的示例代码,用于保护共享资源:
#include <pthread.h>
#include <stdio.h>
int count = 0;
pthread_mutex_t mutex;
void *thread_func(void *arg) {
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock(&mutex);
count++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid1, NULL, thread_func, NULL);
pthread_create(&tid2, NULL, thread_func, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("count = %d
", count);
pthread_mutex_destroy(&mutex);
return 0;
}
在上述示例代码中,两个线程通过竞争的方式增加共享资源count的值。为了保证对count的访问互斥,我们使用了互斥锁pthread_mutex_t mutex。
在每个线程中,我们首先使用pthread_mutex_lock函数获取互斥锁,然后进行对count的操作,最后使用pthread_mutex_unlock函数释放互斥锁。这样就保证了同时只有一个线程能够对count进行操作,避免了数据不一致的问题。
最后,我们使用pthread_mutex_destroy函数销毁互斥锁。