问题
I'm writing a program that creates two threads. Each thread is responsible for reading through one text file, with one char on each line.
The first is formatted like:
h
0
h
0
...
The second is formatted like:
0
i
0
i
0
i
Sometimes there can be multiple letters after each other, or multiple zeros after each other. However, the one certainty is that if there is a letter on one line of one file, the corresponding line of the second file will have a 0, and vice versa.
The threads are supposed to keep reading the file input into a global char array until they reach a zero. At this point, they allow the other thread to take over. And they keep going back and forth until both files are completely read.
At this point, when I run, I get variations of either (1) many h's followed by many i's or (2) (the correct answer) a continuous stream of hihihi's, or (3) sometimes many i's followed by many h's. So, I know that my synchronization methods are off.
Here is an example of one of my threads: (Note both threads are exactly the same, except for the file being opened.)
void *getMessage1()
{
FILE *studentOne = fopen("Student1", "r");
size_t howManyChars;
char *placeHolderChars;
int count = 1;
while (count < 501)
{
placeHolderChars = NULL;
getline(&placeHolderChars, &howManyChars, studentOne);
if(strcmp(placeHolderChars, "0\n") == 0) //if we've reached a zero
{
pthread_mutex_unlock(&lock);
}
else
{ while(1)
{
if(pthread_mutex_trylock(&lock) == 0)
{
break;
}
}
if(strlen(placeHolderChars)>0)
{
placeHolderChars[1] = '\0';
}
strcat(message,placeHolderChars);
}
free(placeHolderChars);
if(feof(studentOne))
{
pthread_mutex_unlock(&lock); //unlock
fclose(studentOne);
break;
}
count++;
}
return 0;
}
Here is my main method:
int main(void)
{
pthread_t id1;
pthread_t id2;
pthread_create((&id1), NULL, getMessage1, NULL);
pthread_create((&id2), NULL, getMessage2, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
int j;
for (j = 0; j < 1001; j++)
{
printf ("%c ",message[j]);
}
return 0;
}
I would appreciate any guidance on how I can better use lock, unlock, wait, and/or signal to create a working synchronization technique with consistent results.
回答1:
Here is one attempt at a program that does what you want. Insufficiently tested, though ;)
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <pthread.h>
using std::cout;
using std::ifstream;
using std::string;
const string FILE1("file1.txt");
const string FILE2("file2.txt");
enum State
{
UNINITIALIZED,
THREAD_ONE_READS,
THREAD_TWO_READS
};
struct ThreadInfo
{
State state;
string filename;
};
State state = UNINITIALIZED;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_func(void* arg)
{
// Open file 'h'.
ThreadInfo ti = *reinterpret_cast<ThreadInfo*>(arg);
ifstream infile;
infile.open (ti.filename.c_str(), std::ifstream::in);
// while (not EOF)
// Read 'h' or 'i': until 0 reached. Wake up other thread.
string line;
getline(infile, line);
while (infile.good())
{
cout << "Thread " << pthread_self() << " read " << line << '\n';
pthread_mutex_lock(&mut);
while (state == ti.state)
{
pthread_cond_wait(&cond, &mut);
}
pthread_mutex_unlock(&mut);
assert(line.length() == 1);
if (line[0] == '0')
{
pthread_mutex_lock(&mut);
state = ti.state;
cout << "Got 0, transferring, setting state to " << state << '\n';
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
else
{
cout << "Read char: " << line << '\n';
}
getline(infile, line);
}
pthread_mutex_lock(&mut);
state = ti.state;
cout << "Finishing thread, transferring, setting state to " << state << '\n';
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
int main()
{
// Create thread 1
// Create thread 2
pthread_t thread_one_handle;
pthread_t thread_two_handle;
state = THREAD_ONE_READS;
int result;
ThreadInfo info1 = { THREAD_TWO_READS, FILE1 };
result = pthread_create(&thread_one_handle, NULL, thread_func, &info1);
assert(result == 0);
ThreadInfo info2 = { THREAD_ONE_READS, FILE2 };
result = pthread_create(&thread_two_handle, NULL, thread_func, &info2);
assert(result == 0);
result = pthread_join(thread_one_handle, NULL);
assert(result == 0);
result = pthread_join(thread_two_handle, NULL);
assert(result == 0);
cout << "main(): joined both worker threads, ending program.\n";
return 0;
}
来源:https://stackoverflow.com/questions/46384349/pthread-synchronization-back-forth-reading-of-two-text-files