【发布时间】:2018-10-15 23:43:30
【问题描述】:
我正在尝试同步读取 5 个文件,以便从一个文件中读取每个字符,然后从下一个文件中读取另一个字符,依此类推。最后一个数组将打印出内容。我可以从文件中读取,但同步已经结束。我试图用一个控制变量来修复它,只在文件打开时运行代码块,但我得到一个不稳定的输出。这是我在关键部分工作的部分
while(!feof(drive1)) {
if(control == 0) {
pthread_mutex_lock(&thread1);
//printf("Mutex lock\n");
c = getc(drive1);
printf("%c", (char)c);
control = 1;
pthread_mutex_unlock(&thread1);
//printf("Mutex unlock\n");
} else if(control == 1) {
pthread_mutex_lock(&thread2);
//printf("Mutex lock\n");
a = getc(drive2);
printf("%c", (char)a);
control = 2;
pthread_mutex_unlock(&thread2);
//printf("Mutex unlock\n");
} else if(control == 2) {
pthread_mutex_lock(&thread3);
//printf("Mutex lock\n");
b = getc(drive3);
printf("%c", (char)b);
control = 3;
pthread_mutex_unlock(&thread3);
//printf("Mutex unlock\n");
} else if(control == 3) {
pthread_mutex_lock(&thread4);
//printf("Mutex lock\n");
d = getc(drive4);
printf("%c", (char)d);
control = 4;
pthread_mutex_unlock(&thread4);
//printf("Mutex unlock\n");
} else if(control == 4) {
pthread_mutex_lock(&thread5);
//printf("Mutex lock\n");
e = getc(drive5);
printf("%c", (char)e);
control = 0;
pthread_mutex_unlock(&thread5);
//printf("Mutex unlock\n");
}
我最初尝试只使用一个线程 1 来锁定和解锁互斥锁,但后来决定创建 5 个线程来查看是否有帮助,但它没有。我还必须为每个文件使用 5 个线程来执行此操作。
pthread_t th1;
pthread_create(&th1, NULL, processing, NULL);
pthread_t th2;
pthread_create(&th2, NULL, processing, NULL);
pthread_t th3;
pthread_create(&th3, NULL, processing, NULL);
pthread_t th4;
pthread_create(&th4, NULL, processing, NULL);
pthread_t th5;
pthread_create(&th5, NULL, processing, NULL);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
pthread_join(th3, NULL);
pthread_join(th4, NULL);
pthread_join(th4, NULL);
输出应该是“1234567890abcdefghij”
更新:基于其中一个 cmets,我修改了代码以使用变量“test”作为关键部分中正在测试的内容。使用此代码,我得到输出 1212。
void* disk1(void* args) {
//Initializing array of files
FILE *drive[5];
drive[0] = fopen("drive1.data", "r");
drive[1] = fopen("drive2.data", "r");
drive[2] = fopen("drive3.data", "r");
drive[3] = fopen("drive4.data", "r");
drive[4] = fopen("drive5.data", "r");
int c;
if(test < initialFileSize * 2) {
pthread_mutex_lock(&thread1);
if(test % 2 == 0) {
c = getc(drive[0]);
printf("%c", (char)c);
test++;
}
if(test % 2 == 1) {
c = getc(drive[1]);
printf("%c", (char)c);
test++;
}
pthread_mutex_unlock(&thread1);
}
}
【问题讨论】:
-
你认为互斥体应该做什么?他们只确保 lock() 和 unlock() 之间的语句发生在一个线程中。他们没有做任何事情来确保线程被赋予相同的时间片,或者以任何特定的顺序运行。
-
那么我将如何实施某种计划。我们不允许使用信号量。
-
由于每个线程只查看自己的互斥体,因此没有太多的互斥。而且由于所有线程都查看共享资源
control而不确保互斥,因此任何人都可以猜测任何给定进程会看到什么。在我的脑海中,我认为您可能需要查看具有单个互斥锁控制对control的访问的条件变量,以及锁定互斥锁的线程,等待条件,测试control是否设置为它们的值(如果没有,则再次等待),并在值指示轮到他们时继续。
标签: c synchronization mutex file-read