Hi, I'm new to C, and an assignment for multithreading was just kind of thrown at me, so I'm kind of lost.

I need to write a program that creates four threads.
The first thread would have to read stdin, writes the char to array of 64 bytes, and after it finishes with this job, it will wake up the second thread, and block. The second array will run, read the data from that array, translate it, pass the result to another array of 64 bytes, it would wake up the first and third thread (which will read the second array), and block itself.

So that's the general idea.

My question is, how would I code the array such that it will be shared by the threads (which will be running different functions in different .c files)? Do I just declare it as global variables and mutex the threads so that they won't be accessing the arrays at the same time?

Sorry if it's kind of confusing, I'm not sure what are the proper (technical) terms to use.

Recommended Answers

All 2 Replies

I think you have to define two arrays and two mutex as global variables such as:
two arrays: 1st_array, 2nd_array
two mutex: 1st_mutex, 2nd_mutex

and we will have three functions as below

void ReaderThread(....) // 1st thread
{
    ....
    lock 1st_mutex;
    if (1st_array is empty) 
    {
          read info from stdin -> put to 1st_arrray
    }
    unlock 1st_mutex;
    delay
    continue;
    ....
}

void TranslateThread(....) // 2nd thread
{
    ....
    lock 1st_mutex;
    try lock 2nd_mutex;
    if (2nd_array is not busy) 
    {
            if (1st_array is not rempty)
            {
                   translate it and pass the result to 2nd_array;
                   empty 1st_array;
            }
            unlock 2nd_mutex;
    }
    unlock 1st_mutex;
    delay
    continue;
    ....
}

void ProcessThread(....) // 3rd thread
{
    ....
    lock 2st_mutex;
    if (this is new result) 
    {
            process 2nd_array;
            empty 2nd_array;
    }
    unlock 2st_mutex;
    delay
    continue;
    ....
}

That's it.
xitrum

thank you~ :) that really cleared up a lot of things for me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.