#include <stdio.h>
#include <pthread.h>
pthread_mutex_t Device_mutex;
int count = 0;
void* thread_func1(void* arg)
{
while (1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread1: %d\n", count);
pthread_mutex_unlock(&Device_mutex);
count++;
sleep(1);
}
return NULL;
}
void* thread_func2(void* arg)
{
while (1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread2: %d\n", count);
pthread_mutex_unlock(&Device_mutex);
count++;
sleep(1);
}
return NULL;
}
int main()
{
pthread_t thread1, thread2;
pthread_mutex_init(&Device_mutex, NULL);
if (pthread_create(&thread1, NULL, thread_func1, NULL) == -1)
{
printf("create thread1 error!\n");
exit(1);
}
sleep(1);
if (pthread_create(&thread2, NULL, thread_func2, NULL) == -1)
{
printf("create thread2 error!\n");
exit(1);
}
sleep(1);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&Device_mutex);
return 0;
}
pthread_mutex_init(&Device_mutex, NULL) 建立鎖。pthread_mutex_lock / pthread_mutex_unlock 保護臨界區(列印與遞增 count)。pthread_create 傳入函數指標,注意型別轉換。pthread_join 阻塞主執行緒直到子執行緒結束(此範例為無限迴圈,實際應用需加入退出機制)。pthread_mutex_destroy 銷毀鎖。gcc -o mutex_demo mutex_demo.c -lpthread
./mutex_demo
輸出將交替顯示 thread1: N 與 thread2: N+1,證明共享變數 count 在鎖保護下安全存取。