尝试实现该程序的关键部分,以便在两个线程之间正确交换,如后面的描述中所述。
我正在尝试为我的操作系统类(class)做一道题。问题是我需要输入两个文件,每个文件都放入各自单独的线程中,它们将读取该文件,直到遇到数字“0”的行。然后另一个线程应该按照相同的规则运行。
该程序应该接受两个文件输入,并通过按特定顺序连接文件中的两个输入来找出消息,然后在解密后打印出输出。
这两个文件的输入如下所示
Person1 Person2
--------- ----------
t 0
0 h
i 0
s 0
0 i
0 s
0 a
t 0
e 0
0 s
t 0
上述输入应产生具有此输出的字符串
Example: “thisisatest”
当前分配出现的问题是它没有在两个线程之间正确交换并处于无限循环中。
就像我上面所说的,我正在尝试使用互斥体和 Pthreads 来解决这个分配
下面是我的代码的当前实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static char *charArray[1000];
void *threadPerson1(void *value){
FILE *fPTR;
char buffer[2];
char *fileName = "Person1.txt";
fPTR = fopen(fileName, "r");
if (fPTR == NULL){
printf("was unable to open: %s\n", fileName);
return NULL;
}
while(1){
//Entering the critical section
pthread_mutex_lock(&mutex);
fscanf(fPTR, "%s", buffer);
printf("This is Person1: %s\n", buffer);
if(buffer != "0"){
charArray[count] = buffer;
count++;
}
if(buffer == "0"){
pthread_mutex_unlock(&mutex);
}
//exiting the critical section
}
}
void *threadPerson2(void *value){
FILE *fPTR;
char buffer[2];
char *fileName = "Person2.txt";
fPTR = fopen(fileName, "r");
if (fPTR == NULL){
printf("was unable to open: %s\n", fileName);
return NULL;
}
while(1){
//entering the critical section
pthread_mutex_lock(&mutex);
fscanf(fPTR, "%s", buffer);
printf("This is Person2: %s\n", buffer);
if(buffer != "0"){
charArray[count] = buffer;
count++;
}
if(feof(fPTR)){
printf("read end of file of: Person2\n");
fclose(fPTR);
return NULL;
}
if(buffer == "0"){
pthread_mutex_unlock(&mutex);
}
//exiting the critical section
}
}
int main(int argc, char **argv){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, threadPerson1, NULL);
pthread_create(&thread2, NULL, threadPerson2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
for(int x = 0; x < 1000; x++){
if(charArray[x] == NULL){
printf("\n");
break;
}else{
printf("%s", charArray[x]);
}
}
return 0;
}
最佳答案
您的程序中至少有两处不正确。首先,如果一个线程释放互斥锁,则不能保证调度程序将允许另一个线程运行,释放线程很可能会继续并立即重新获取互斥锁。使用条件变量,阅读其联机帮助页。另外,这里还有一些示例,特别是 4-8:Multithreaded programming guide
第二,当到达文件末尾时,需要释放互斥体来清理。最简单的方法就是我们在 C++ 中所说的 RAII,即使用资源句柄,当句柄对象超出范围时释放互斥锁。你可以在 C 中做类似的事情,例如通过注册一个清理函数,或者“转到”到函数末尾并从那里调用清理代码。
关于临界区同步C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162471/