互斥锁的创建两种方式
1.动态方式
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
FILE *fp;
void *func2(void *arg)
{
pthread_detach(pthread_self());
printf("this is func2 thread\n");
char str2[]="i write func2 line\n";
char c;
int i=0;
while(1)
{
while(i<strlen(str2))
{
c=str2[i];
fputc(c,fp);
usleep(1);
i++;
}
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg)
{
pthread_detach(pthread_self());
printf("this is func thread\n");
char str[]="i write func line\n";
char c;
int i=0;
while(1)
{
while(i<strlen(str))
{
c=str[i];
fputc(c,fp);
i++;
usleep(1);
}
i=0;
usleep(1);
}
pthread_exit("func exit");
}
int main(int argc, char **argv)
{
pthread_t tid,tid2;
void *retv;
int i;
fp=fopen("2.txt","a+");
if(fp==NULL)
{
printf("Error opening");
return 0;
}
pthread_create(&tid, NULL,func,NULL);
pthread_create(&tid2, NULL,func2,NULL);
while(1)
{
sleep(1);
}
}
从结果2.txt可以看出 写入文件的内容是乱的,因为文件是临界资源,两个线程同时写入会乱套,因此引入了互斥锁的概念
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;
FILE *fp;
void *func2(void *arg)
{
pthread_detach(pthread_self());
printf("this is func2 thread\n");
char str2[]="i write func2 line\n";
char c;
int i=0;
while(1)
{
pthread_mutex_lock(&mutex); //上锁
while(i<strlen(str2))
{
c=str2[i];
fputc(c,fp);
usleep(1);
i++;
}
pthread_mutex_unlock(&mutex); //解锁
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg)
{
pthread_detach(pthread_self());
printf("this is func thread\n");
char str[]="i write func line\n";
char c;
int i=0;
while(1)
{
pthread_mutex_lock(&mutex); //上锁
while(i<strlen(str))
{
c=str[i];
fputc(c,fp);
i++;
usleep(1);
}
pthread_mutex_unlock(&mutex); //解锁
i=0;
usleep(1);
}
pthread_exit("func exit");
}
int main(int argc, char **argv)
{
pthread_t tid,tid2;
void *retv;
int i;
fp=fopen("2.txt","a+");
if(fp==NULL)
{
printf("Error opening");
return 0;
}
pthread_create(&tid, NULL,func,NULL);
pthread_create(&tid2, NULL,func2,NULL);
while(1)
{
sleep(1);
}
}
写入之前上锁,写入之后解锁
可以看出文件中的写入内容是完整的。
2.静态方式