定义一个全局变量,char str[] = "123456",要求定义两个线程:线程A, 线程B
-
要求A线程循环打印全局字符串str;
-
要求B线程循环倒置全局字符串str:将str中的内容倒置为"654321",再倒置为"123456"....
注意:是倒置不是倒着打印
-
要求A线程打印出的str字符串内容为:123456或者654321。
不允许出现乱序,例如:
#include<stdio.h> #include<unistd.h> #include<pthread.h> #include<string.h> char str[]="123456"; pthread_mutex_t mutex; void* callA(void *arg) { while(1) { pthread_mutex_lock(&mutex); //上锁 printf("%s\n",str); pthread_mutex_unlock(&mutex); //解锁 } pthread_exit(NULL); } void* callB(void *arg) { int len = strlen(str); char temp; while(1) { pthread_mutex_lock(&mutex); //上锁 //倒置 for(int i=0;i<len/2;i++) { temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; } pthread_mutex_unlock(&mutex); //解锁 } pthread_exit(NULL); } int main(int argc, const char *argv[]) { printf("start\n"); //创建互斥锁 pthread_mutex_init(&mutex,NULL); //创建线程 pthread_t tidA; pthread_t tidB; if(pthread_create(&tidA,NULL,callA,NULL) != 0) { perror("pthread_create"); return -1; } if(pthread_create(&tidB,NULL,callB,NULL) != 0) { perror("pthread_create"); return -1; } pthread_join(tidA,NULL); pthread_join(tidB,NULL); return 0; }要求用两个线程拷贝一张图片,A线程拷贝前半部分,B线程拷贝后半部分
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
pthread_mutex_t mutex; //锁
int fd_r;
int fd_w;
int size; //大小
//拷贝前半部分
void *copyA_part(void *arg)
{
pthread_mutex_lock(&mutex); //上锁
//前半
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
char c[2];
for(int i=0;i<size/2+1;i++)
{
int res = read(fd_r,c,sizeof(c)-1);
if(0 >=res)
break;
write(fd_w,c,res);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_exit(NULL);
}
//拷贝后半部分
void *copyB_part(void *arg)
{
pthread_mutex_lock(&mutex); //上锁
//后半
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
char c[2];
for(int i=size/2;i<size;i++)
{
int res = read(fd_r,c,sizeof(c)-1);
if(0 >= res)
break;
write(fd_w,c,res);
}
pthread_mutex_unlock(&mutex); //解锁
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建互斥锁
pthread_mutex_init(&mutex,NULL);
//打开图片文件
fd_r = open("./1.png",O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
/*
//图片大小
struct stat buf;
int a=stat("./1.png",&buf);
int size = buf.size;
*/
size = lseek(fd_r,0,SEEK_END); //大小
//写入图片
fd_w = open("./copy.png",O_WRONLY|O_TRUNC|O_CREAT,0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
//创建线程A、B
pthread_t copyA,copyB;
if(pthread_create(©A,NULL,copyA_part,NULL) != 0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(©B,NULL,copyB_part,NULL) != 0)
{
perror("pthread_create");
return -1;
}
pthread_join(copyA,NULL);
pthread_join(copyB,NULL);
close(fd_r);
close(fd_w);
pthread_mutex_destroy(&mutex);
return 0;
}
![]()
这篇博客探讨了如何使用C语言实现多线程同步,具体包括线程A循环打印全局字符串并保持其正确性,线程B循环倒置字符串。同时,还介绍了如何通过两个线程分别拷贝图片文件的前半部分和后半部分,确保文件完整无乱序。示例代码展示了pthread库在多线程同步中的应用。

被折叠的 条评论
为什么被折叠?



