【Linux】线程同步和互斥
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
在Linux中,线程同步和互斥可以通过多种方式实现,其中常用的包括互斥锁(mutexes)、条件变量(conditions variables)、读写锁(reader-writer locks)和信号量(semaphores)。
以下是使用互斥锁实现线程同步的示例代码:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared = 0;
void* thread_function(void* arg) {
// 锁定互斥锁
pthread_mutex_lock(&mutex);
shared++;
printf("Thread %lu shared is %d\n", pthread_self(), shared);
// 解锁互斥锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t thread1, thread2;
// 创建线程
pthread_create(&thread1, NULL, &thread_function, NULL);
pthread_create(&thread2, NULL, &thread_function, NULL);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
在这个例子中,我们定义了一个名为shared
的共享资源和一个互斥锁mutex
。每个线程在访问shared
之前都会尝试锁定互斥锁,访问完毕后解锁。这样可以确保同一时刻只有一个线程可以修改shared
变量。
评论已关闭