我正在学习操作系统的工作原理,从 Raspberry Pi 上的 Linux 开始。目前,我正在编写一个使用 pthread 创建多个线程并相互通信的程序。在这个程序中,将有 2 个线程(如果算上 main(),则为 3 个),1 个在写,另一个在读,两个线程使用一个共同的结构来读写,互斥体相互发出信号(通过检查锁,锁定和解锁)。
要检查线程通信,我会这样做:写入线程将从名为 randStrings.txt 的文件中读取,计算“e”的数量和每行的总字符数,然后将这两个数字放在一个公共结构中。
读取线程将写入一个名为 resultStrings.txt 的文件,从公共结构中读取,然后写入“e”的数量(如果 e 计数为!= 0),否则,为该行的总长度写入“-”。
到目前为止,我的线程可以相互交谈,但是,我不能执行 pthread_join() 在 2 个线程之间来回切换。
这是我的代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
/*
The following structure contains the necessary information
to allow the function "dotprod" to access its input data and
place its output into the structure.
*/
typedef struct
{
int e; //number of e
int c; //number of character
} DOTDATA;
/* Define globally accessible variables and a mutex */
#define NUMTHRDS 1
DOTDATA dotstr;
pthread_t callThd[NUMTHRDS];
//Initialize mutex
pthread_mutex_t mutex_write = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_read = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_critical = PTHREAD_MUTEX_INITIALIZER;
void *writeMutex(void *arg)
{
int count;
int e_count;
int term_sig;
FILE *readf;
char my_lines[100];
char ch;
signed int numbers[2];
int i;
char s[50];
term_sig = -1;
//unlock write region
printf("Write thread: Unlocking write mutex\n");
pthread_mutex_unlock (&mutex_write);
//unlock critical region
printf("Write thread: Unlocking critical mutex\n");
pthread_mutex_unlock (&mutex_critical);
readf = fopen("randStrings.txt", "r");
if (readf == NULL){
printf("Error opening file");
}
//Read the file
while ((fgets(my_lines, 33, readf))!=NULL)
{
e_count = 0;
count = 0;
my_lines[sizeof(my_lines) - 1] = '\0';
printf("%s\n", my_lines);
for (i = 0; i < sizeof(my_lines); i++){
if(my_lines[i] == '\0') break;
else if (my_lines[i]=='e'){
e_count++;
}
else{ //if (my_lines[i] >= 'a' && my_lines[i] <= 'z'){
count++;
}
}
//lock write
printf("Write thread: Locking write mutex\n");
while(pthread_mutex_lock (&mutex_write)!=0)
{
printf("Write thread: Locking write mutex\n");
}
//lock critical region
printf("Write thread: Locking critical mutex\n");
while(pthread_mutex_lock (&mutex_critical)!=0)
{
printf("Write thread: Locking critical mutex\n");
}
printf("Write thread: Writing value\n");
//write to global varibales
dotstr.e = e_count;
dotstr.c = count;
//unlock critical region
printf("Write thread: Unlocking critical mutex\n");
pthread_mutex_unlock (&mutex_critical);
//unlock read
printf("Write thread: Unlocking read mutex\n");
pthread_mutex_unlock (&mutex_read);
printf("\nParent(%d) send value: [%d, %d]\n", getpid(), e_count, count);
printf("Joining thread!\n");
if((pthread_join(callThd[1], NULL)) !=0)
{
printf("Error joining with reading thread!\n");
}
}
fclose(readf);
//lock write
printf("Write thread: Locking write, end signal, mutex\n");
while(pthread_mutex_lock (&mutex_write)!=0)
{
printf("Write thread: Locking write, end signal, mutex\n");
}
//lock critical region
printf("Write thread: Locking critical, end signal, mutex\n");
while(pthread_mutex_lock (&mutex_critical)!=0)
{
printf("Write thread: Locking critical, end signal, mutex\n");
}
printf("Read thread: reading value\n");
//write to global variables
dotstr.e = term_sig;
dotstr.c = term_sig;
//unlock critical region
printf("Write thread: Unlocking critical, end signal, mutex\n");
pthread_mutex_unlock (&mutex_critical);
//unlock read
printf("Write thread: Unlocking read, end signal, mutex\n");
pthread_mutex_unlock (&mutex_read);
pthread_exit(NULL);
}
void *readMutex(void *arg)
{
char readBuffer[1000];
FILE *readf1;
int numbers_e;
int numbers_c;
int sig;
int j;
sig--;
//open the result file.
readf1 = fopen("resultStrings.txt", "w");
while(numbers_e != sig && numbers_c != sig)
{
//unlock read
printf("Read thread: Unlocking read mutex\n");
pthread_mutex_unlock (&mutex_read);
//lock read
printf("Read thread: Locking read mutex\n");
while(pthread_mutex_lock (&mutex_read)!=0)
{
printf("Read thread: Locking read mutex\n");
}
//lock critical region
printf("Read thread: Locking critical mutex\n");
while(pthread_mutex_lock (&mutex_critical)!=0)
{
printf("Read thread: Locking critical mutex\n");
}
printf("Read thread: Reading value\n");
//read global varibales
numbers_e = dotstr.e;
numbers_c = dotstr.c;
//unlock critical region
printf("Read thread: Unlocking critical mutex\n");
pthread_mutex_unlock (&mutex_critical);
//unlock read
printf("Read thread: Unlocking write mutex\n");
pthread_mutex_unlock (&mutex_write);
readBuffer[0] = 0; //reset readBuffer
//Un-bundling data
printf("\nConsumer (%d) Bundle received: [%i, %i]\n", getpid(), numbers_e, numbers_c);
//readBuffer[0] = 0;
if(numbers_e!= 0) {
for (j = 0; j < numbers_e; j++){
readBuffer[j] = 'e';
}
readBuffer[j+1] = '\0';
for (j = 0; j < sizeof(readBuffer); j++) {
if (readBuffer[j] == 'e'){
fprintf(readf1, "%c", readBuffer[j]);
printf("%c", readBuffer[j]);
}
}
fprintf(readf1, "\n");
printf("\n\n");
}
else if(numbers_c != 0) {
for (j = 0; j < numbers_c; j++){
readBuffer[j] = '-';
}
readBuffer[j+1] = '\0';
for (j = 0; j < sizeof(readBuffer) - 1; j++) {
if (readBuffer[j] == '-'){
fprintf(readf1, "%c", readBuffer[j]);
printf("%c", readBuffer[j]);
}
}
fprintf(readf1, "\n");
printf("\n");
}
if((pthread_join(callThd[0], NULL)) !=0)
{
printf("Error joining with writing thread!\n");
}
}
fclose(readf1);
pthread_exit(NULL);
}
// Main program
int main (int argc, char *argv[])
{
//other variables
pthread_attr_t attr;
void *status;
printf("Locking all mutexes...\n");
pthread_mutex_lock (&mutex_read);
pthread_mutex_lock (&mutex_critical);
pthread_mutex_lock (&mutex_write);
//Threads attribute
pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
//Create threads
printf("Creating writing thread...\n");
pthread_create(&callThd[1], &attr, readMutex, NULL);
pthread_create(&callThd[0], &attr, writeMutex, NULL);
printf("Creating reading thread...\n");
for(;;){
}
printf("Program finished, deleting all mutexes...\n");
pthread_mutex_destroy(&mutex_write);
pthread_mutex_destroy(&mutex_read);
pthread_mutex_destroy(&mutex_critical);
pthread_exit(NULL);
}
输出:
Locking all mutexes...
Creating writing thread...
Creating reading thread...
Write thread: Unlocking write mutex
Write thread: Unlocking critical mutex
kuuxfithomqjnyxqsdpagdue
Write thread: Locking write mutex
Write thread: Locking critical mutex
Write thread: Writing value
Write thread: Unlocking critical mutex
Write thread: Unlocking read mutex
Parent(2917) send value: [1, 24]
Read thread: Unlocking read mutex
Read thread: Locking read mutex
Read thread: Locking critical mutex
Read thread: Reading value
Read thread: Unlocking critical mutex
Read thread: Unlocking write mutex
Consumer (2917) Bundle received: [1, 24]
e
Joining thread!
Error joining with reading thread!
czfnvphqnmzhunukxhjvxbyncerxjba
Write thread: Locking write mutex
Write thread: Locking critical mutex
Write thread: Writing value
Write thread: Unlocking critical mutex
Write thread: Unlocking read mutex
Parent(2917) send value: [1, 31]
Joining thread!
Error joining with reading thread!
gzxwgojtnrnblyyshtqjrelwvif
Write thread: Locking write mutex
^C
编辑 2:感谢 darron 指出我的错。通过在我不需要的地方使用指针,他们弄乱了我的结果。
现在我发现了另一个问题,当使用 pthread_join() 在 2 个线程之间来回跳转时,它只能跳转一次。读取线程已完成处理来自写入线程的数据,写入线程仍有更多数据要发送,但它永远不能再次调用读取线程来执行此操作。有没有办法可以在 2 个线程之间来回切换?也许没有 pthread_join() 有一种更简单的方法可以做到这一点?
另外,如何在 2 个线程完成工作后停止程序?现在,我必须在 main 中放置一个无限循环以保持它们运行而不会在线程完成之前破坏所有互斥锁,但是除了 CTRL + C 之外没有其他方法可以阻止它们。