无锁时线程对全局内存的操作

互斥锁控制全局内存
互斥锁相关函数功能

代码演示
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>
char buffer[101]; // 申请一块全局内存
pthread_mutex_t mutex; // 申请一个互斥锁
void *pthfun(void *arg)
{
for(int ii=0;ii<3;ii++)
{
printf("%d:%ld:lock...\n",time(0),(long)arg);
pthread_mutex_lock(&mutex); // 上锁
printf("%d:%ld:lock ok.\n",time(0),(long)arg);
sprintf(buffer,"%d:%ld,%d",time(0),pthread_self(),ii);
sleep(5);
pthread_mutex_unlock(&mutex); // 解锁
printf("%d:%ld:unlock...\n",time(0),(long)arg);
usleep(100); // 延迟的目的是避免因互斥锁锁优先唤醒问题而一直被一个线程上锁
}
}
int main()
{
pthread_mutex_init(&mutex,NULL); // 初始化锁
pthread_t pthid1,pthid2;
pthread_create(&pthid1,NULL,pthfun,(void*)1); // 创建线程1
pthread_create(&pthid2,NULL,pthfun,(void*)2); // 创建线程2
pthread_join(pthid1,NULL);
pthread_join(pthid2,NULL);
pthread_mutex_destroy(&mutex); // 销毁互斥锁
return 0;
}
结果演示