【探索Linux】P.20(多线程 | 线程互斥 | 互斥锁 | 死锁 | 资源饥饿)
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_function(void* arg) {
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&mutex);
printf("Thread locked: %d\n", i);
sleep(1); // 模拟耗时操作
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, &thread_function, NULL);
thread_function(NULL); // 同时执行
pthread_join(thread, NULL);
return 0;
}
这段代码演示了如何使用互斥锁来避免两个线程同时访问共享资源。主线程和新创建的线程都执行thread_function
函数,它通过互斥锁来确保输出有序,每隔1秒打印一次,直到i增加到5。这里使用了pthread_mutex_lock
和pthread_mutex_unlock
来锁定和解锁互斥量。当互斥锁被锁定时,其他线程将无法访问被保护的代码块。
评论已关闭