c - 线程间通信,线程之间的切换

标签 c multithreading

我正在学习操作系统的工作原理,从 Raspberry Pi 上的 Linux 开始。目前,我正在编写一个程序,该程序使用 pthread 创建多个线程并相互通信。在这个程序中,将有 2 个线程(如果算上 main() 则为 3 个),1 个正在写入,另一个正在读取,两个线程都使用公共(public)结构体进行读写,并使用互斥体相互发送信号(通过检查锁,锁定和解锁)。

要检查线程通信,我会执行以下操作: 写入线程将从名为 randStrings.txt 的文件中读取,计算“e”的数量和每行的字符总数,然后将这两个数字放入一个公共(public)结构中。

读取线程将写入一个名为 resultStrings.txt 的文件,从公共(public)结构中读取,然后写入 '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: 感谢达伦指出我的错误。通过在我不需要的地方使用指针,他们弄乱了我的结果。

现在我发现了另一个问题,当使用 pthread_join() 在两个线程之间来回跳转时,它只能跳转一次。读取线程已完成处理来自写入线程的数据,并且写入线程仍然有更多数据要发送,但它永远不能再次调用读取线程来执行此操作。有没有办法可以在两个线程之间来回切换?也许有一种更简单的方法可以在不使用 pthread_join() 的情况下执行此操作?

另外,当两个线程完成工作后如何停止程序?现在,我必须在 main 中放置一个无限循环,以保持它们运行,而不会在线程完成之前销毁所有互斥体,但除了 CTRL + C 之外,没有办法阻止它们。

最佳答案

当您确实不需要它们时,您创建了很多指针(“*”字符)。您似乎不知道它们的用途...如果您将某些内容用作数字,只需使用“int”,而不是“int *”...

关于c - 线程间通信,线程之间的切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19614086/

相关文章:

CUDA:在内核执行时修改主机的映射内存

c - 以下C代码有什么问题

Java - Swing JLabel 更新太快?

java - 自定义 Runnable 实现,用于检查每行代码之间的 Thread.currentThread().isInterrupted()

c++ - 线程池(大概)锁定条件变量和互斥量的问题

c - 使用 char 矩阵作为函数的参数

c - 如何使用标准库在 GNU C 中生成 A 到 B 之间的伪随机数(A,B 是整数)

Bazel 中基于编译器(gcc vs clang)的配置 "copts"

mysql - Qt4:如何在线程之间传输mysql查询?

multithreading - 如何使用 future 进行多线程处理?