I am trying to implement the Producer-Consumer problem operating system using semaphore and pthread. But my output is totally different from expected. Here is my code:
#include<iostream>
#include<pthread.h>
#include<fstream>
#include<unistd.h>
#include<queue>
// define queue size
#define QUEUE_SIZE 5
// declare and initialize semaphore and read/write counter
static int semaphore = 1;
static int counter = 0;
// Queue for saving characters
static std::queue<char> charQueue;
// indicator for end of file
static bool endOfFile = false;
// save arrays
char consumerArray1[100];
char consumerArray2[100];
// function to wait for semaphore
void wait()
{
while(semaphore<=0);
semaphore--;
}
// function to signal the wait function
void signal()
{
semaphore++;
}
void *Producer(void *ptr)
{
int i=0;
std::ifstream input("string.txt");
char temp;
while(input>>temp)
{
wait();
charQueue.push(temp);
//std::cout<<"Producer:\nCounter: "<<counter<<" Semaphore: "<<semaphore<<std::endl;
counter++;
std::cout<<"Procuder Index: "<<i<<std::endl;
i++;
signal();
sleep(2);
}
endOfFile = true;
pthread_exit(NULL);
}
void *Consumer1(void *ptr)
{
std::cout<<"Entered consumer 1:"<<std::endl;
int i = 0;
while(counter<=0);
while(!endOfFile)
{
while(counter<=0);
wait();
//std::cout<<"Consumer1:\nCounter: "<<counter<<" Semaphore: "<<semaphore<<std::endl;
consumerArray1[i] = charQueue.front();
charQueue.pop();
i++;
counter--;
std::cout<<"Consumer1 index:"<<i<<" char: "<<consumerArray1[i]<<std::endl;
signal();
sleep(2);
}
consumerArray1[i] = '\0';
pthread_exit(NULL);
}
void *Consumer2(void *ptr)
{
std::cout<<"Entered consumer 2:"<<std::endl;
int i = 0;
while(counter<=0);
while(!endOfFile)
{
while(counter<=0);
wait();
//std::cout<<"Consumer2:\nCounter: "<<counter<<" Semaphore: "<<semaphore<<std::endl;
consumerArray2[i] = charQueue.front();
charQueue.pop();
i++;
counter--;
std::cout<<"Consumer2 index: "<<i<<" char: "<<consumerArray2[i]<<std::endl;
signal();
sleep(4);
}
consumerArray2[i] = '\0';
pthread_exit(NULL);
}
int main()
{
pthread_t thread[3];
pthread_create(&thread[0],NULL,Producer,NULL);
int rc = pthread_create(&thread[1],NULL,Consumer1,NULL);
if(rc)
{
std::cout<<"Thread not created"<<std::endl;
}
pthread_create(&thread[2],NULL,Consumer2,NULL);
pthread_join(thread[0],NULL);pthread_join(thread[1],NULL);pthread_join(thread[2],NULL);
std::cout<<"First array: "<<consumerArray1<<std::endl;
std::cout<<"Second array: "<<consumerArray2<<std::endl;
pthread_exit(NULL);
}
The problem is my code, in some runs freezes(probably in an infinite loop) after the entire file has been read. And also both of the consumer functions read the same words even though I am popping it out after reading. Also the part of printing the array element that has been read just prints blank. Why are these problems happening? I am new to threads(as in coding using threads, I know theoretical concepts of threads) so please help me with this problem.
The pthreads standard prohibits accessing an object in one thread while another thread is, or might be, modifying it. Your wait and signal functions violate this rule by modifying semaphore (in signal) while a thread calling wait might be accessing it. You do this with counter as well.
If what you were doing in signal and wait were legal, you wouldn't need signal and wait. You could just access the queue directly the same way you access semaphore directly. If the queue needs protection (as I hope you know it does) then semaphore needs protection too and for exactly the same reason.
The compiler is permitted to optimize this code:
while(semaphore<=0);
To this code:
if (semaphore<=0) { while (1); }
Why? Because it knows that no other thread can possibly modify semaphore while this thread could be accessing it since that is prohibited by the standard. Therefore, there is no reason to read more than once.
You need to use actual sempahores and/or locks.
Related
I am implementing a producer-consumer problem using pthreads and semaphore. I have 1 Producer and 2 Consumers. My Producer reads characters one by one from a file and enqueues them into a circular queue. I want the consumers to read from the queue and store into separate arrays. I want the reading in such a way that the first consumer reads 2 characters and the second consumer reads every 3rd character. I am trying to do this using pthread_cond_wait() but it is not working out. This is my code:
#include<iostream>
#include<pthread.h>
#include<fstream>
#include<unistd.h>
#include<semaphore.h>
#include<queue>
#include "circular_queue"
// define queue size
#define QUEUE_SIZE 5
// declare and initialize semaphore and read/write counter
static sem_t mutex,queueEmptyMutex;
//static int counter = 0;
// Queue for saving characters
static Queue charQueue(QUEUE_SIZE);
//static std::queue<char> charQueue;
// indicator for end of file
static bool endOfFile = false;
// save arrays
static char consumerArray1[100];
static char consumerArray2[100];
static pthread_cond_t cond;
static pthread_mutex_t cond_mutex;
static bool thirdCharToRead = false;
void *Producer(void *ptr)
{
int i=0;
std::ifstream input("string.txt");
char temp;
while(input>>temp)
{
std::cout<<"reached here a"<<std::endl;
sem_wait(&mutex);
std::cout<<"reached here b"<<std::endl;
if(!charQueue.full())
{
charQueue.enQueue(temp);
}
sem_post(&queueEmptyMutex);
sem_post(&mutex);
i++;
sleep(4);
}
endOfFile = true;
sem_post(&queueEmptyMutex);
pthread_exit(NULL);
}
void *Consumer1(void *ptr)
{
int i = 0;
sem_wait(&queueEmptyMutex);
bool loopCond = endOfFile;
while(!loopCond)
{
std::cout<<"consumer 1 loop"<<std::endl;
if(endOfFile)
{
loopCond = charQueue.empty();
std::cout<<loopCond<<std::endl;
sem_post(&queueEmptyMutex);
}
sem_wait(&queueEmptyMutex);
sem_wait(&mutex);
if(!charQueue.empty())
{
consumerArray1[i] = charQueue.deQueue();
i++;
if(i%2==0)
{
pthread_mutex_lock(&cond_mutex);
std::cout<<"Signal cond. i = "<<i<<std::endl;
thirdCharToRead = true;
pthread_mutex_unlock(&cond_mutex);
pthread_cond_signal(&cond);
}
}
if(charQueue.empty()&&endOfFile)
{
sem_post(&mutex);
sem_post(&queueEmptyMutex);
break;
}
sem_post(&mutex);
sleep(2);
std::cout<<"consumer 1 loop end"<<std::endl;
}
consumerArray1[i] = '\0';
pthread_exit(NULL);
}
void *Consumer2(void *ptr)
{
int i = 0;
sem_wait(&queueEmptyMutex);
bool loopCond = endOfFile;
while(!loopCond)
{
std::cout<<"consumer 2 loop"<<std::endl;
if(endOfFile)
{
loopCond = charQueue.empty();
std::cout<<loopCond<<std::endl;
sem_post(&queueEmptyMutex);
}
sem_wait(&queueEmptyMutex);
sem_wait(&mutex);
if(!charQueue.empty())
{
pthread_mutex_lock(&cond_mutex);
while(!thirdCharToRead)
{
std::cout<<"Waiting for condition"<<std::endl;
pthread_cond_wait(&cond,&cond_mutex);
}
std::cout<<"Wait over"<<std::endl;
thirdCharToRead = false;
pthread_mutex_unlock(&cond_mutex);
consumerArray2[i] = charQueue.deQueue();
i++;
}
if(charQueue.empty()&& endOfFile)
{
sem_post(&mutex);
sem_post(&queueEmptyMutex);
break;
}
sem_post(&mutex);
std::cout<<"consumer 2 loop end"<<std::endl;
sleep(2);
}
consumerArray2[i] = '\0';
pthread_exit(NULL);
}
int main()
{
pthread_t thread[3];
sem_init(&mutex,0,1);
sem_init(&queueEmptyMutex,0,1);
pthread_mutex_init(&cond_mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&thread[0],NULL,Producer,NULL);
int rc = pthread_create(&thread[1],NULL,Consumer1,NULL);
if(rc)
{
std::cout<<"Thread not created"<<std::endl;
}
pthread_create(&thread[2],NULL,Consumer2,NULL);
pthread_join(thread[0],NULL);pthread_join(thread[1],NULL);pthread_join(thread[2],NULL);
std::cout<<"First array: "<<consumerArray1<<std::endl;
std::cout<<"Second array: "<<consumerArray2<<std::endl;
sem_destroy(&mutex);
sem_destroy(&queueEmptyMutex);
pthread_exit(NULL);
}
The problem I am having is after one read, consumer 2 goes into infinite loop in the while(!thirdCharToRead). Is there any better way to implement this?
Okay, let's start with this code:
std::cout<<"Wait over"<<std::endl;
pthread_mutex_unlock(&cond_mutex);
thirdCharToRead = false;
This code says that cond_mutex does not protect thirdCharToRead from concurrent access. Why? Because it modifies thirdCharToRead without holding that mutex.
Now look at this code:
pthread_mutex_lock(&cond_mutex);
while(!thirdCharToRead)
{
std::cout<<"Waiting for condition"<<std::endl;
pthread_cond_wait(&cond,&cond_mutex);
}
Now, the while loop checks thirdCharToRead, so we must hold whatever lock protects thirdCharToRead from concurrent access when we test it. But the while loop will loop forever if thirdCharToRead stays locked for the whole loop since no other thread could ever change it. Thus, this code only makes sense if somewhere in the loop we release the lock that protects thirdCharToRead, and the only lock we release in the loop is cond_mutex in the call to pthread_cond_wait.
So this code only makes sense if cond_mutex protects thirdCharToRead.
Houston, we have a problem. One chunk of code says cond_mutex does not protect thirdCharToRead and one chunk of code says cond_mutex does protect thirdCharToRead.
I need feedback on my code for following statement, am I on right path?
Problem statement:
a. Implement a semaphore class that has a private int and three public methods: init, wait and signal. The wait and signal methods should behave as expected from a semaphore and must use Peterson's N process algorithm in their implementation.
b. Write a program that creates 5 threads that concurrently update the value of a shared integer and use an object of semaphore class created in part a) to ensure the correctness of the concurrent updates.
Here is my working program:
#include <iostream>
#include <pthread.h>
using namespace std;
pthread_mutex_t mid; //muted id
int shared=0; //global shared variable
class semaphore {
int counter;
public:
semaphore(){
}
void init(){
counter=1; //initialise counter 1 to get first thread access
}
void wait(){
pthread_mutex_lock(&mid); //lock the mutex here
while(1){
if(counter>0){ //check for counter value
counter--; //decrement counter
break; //break the loop
}
}
pthread_mutex_unlock(&mid); //unlock mutex here
}
void signal(){
pthread_mutex_lock(&mid); //lock the mutex here
counter++; //increment counter
pthread_mutex_unlock(&mid); //unlock mutex here
}
};
semaphore sm;
void* fun(void* id)
{
sm.wait(); //call semaphore wait
shared++; //increment shared variable
cout<<"Inside thread "<<shared<<endl;
sm.signal(); //call signal to semaphore
}
int main() {
pthread_t id[5]; //thread ids for 5 threads
sm.init();
int i;
for(i=0;i<5;i++) //create 5 threads
pthread_create(&id[i],NULL,fun,NULL);
for(i=0;i<5;i++)
pthread_join(id[i],NULL); //join 5 threads to complete their task
cout<<"Outside thread "<<shared<<endl;//final value of shared variable
return 0;
}
You need to release the mutex while spinning in the wait loop.
The test happens to work because the threads very likely run their functions start to finish before there is any context switch, and hence each one finishes before the next one even starts. So you have no contention over the semaphore. If you did, they'd get stuck with one waiter spinning with the mutex held, preventing anyone from accessing the counter and hence release the spinner.
Here's an example that works (though it may still have an initialization race that causes it to sporadically not launch correctly). It looks more complicated, mainly because it uses the gcc built-in atomic operations. These are needed whenever you have more than a single core, since each core has its own cache. Declaring the counters 'volatile' only helps with compiler optimization - for what is effectively SMP, cache consistency requires cross-processor cache invalidation, which means special processor instructions need to be used. You can try replacing them with e.g. counter++ and counter-- (and same for 'shared') - and observe how on a multi-core CPU it won't work. (For more details on the gcc atomic ops, see https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/_005f_005fatomic-Builtins.html)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>
class semaphore {
pthread_mutex_t lock;
int32_t counter;
public:
semaphore() {
init();
}
void init() {
counter = 1; //initialise counter 1 to get first access
}
void spinwait() {
while (true) {
// Spin, waiting until we see a positive counter
while (__atomic_load_n(&counter, __ATOMIC_SEQ_CST) <= 0)
;
pthread_mutex_lock(&lock);
if (__atomic_load_n(&counter, __ATOMIC_SEQ_CST) <= 0) {
// Someone else stole the count from under us or it was
// a fluke - keep trying
pthread_mutex_unlock(&lock);
continue;
}
// It's ours
__atomic_fetch_add(&counter, -1, __ATOMIC_SEQ_CST);
pthread_mutex_unlock(&lock);
return;
}
}
void signal() {
pthread_mutex_lock(&lock); //lock the mutex here
__atomic_fetch_add(&counter, 1, __ATOMIC_SEQ_CST);
pthread_mutex_unlock(&lock); //unlock mutex here
}
};
enum {
NUM_TEST_THREADS = 5,
NUM_BANGS = 1000
};
// Making semaphore sm volatile would be complicated, because the
// pthread_mutex library calls don't expect volatile arguments.
int shared = 0; // Global shared variable
semaphore sm; // Semaphore protecting shared variable
volatile int num_workers = 0; // So we can wait until we have N threads
void* fun(void* id)
{
usleep(100000); // 0.1s. Encourage context switch.
const int worker = (intptr_t)id + 1;
printf("Worker %d ready\n", worker);
// Spin, waiting for all workers to be in a runnable state. These printouts
// could be out of order.
++num_workers;
while (num_workers < NUM_TEST_THREADS)
;
// Go!
// Bang on the semaphore. Odd workers increment, even decrement.
if (worker & 1) {
for (int n = 0; n < NUM_BANGS; ++n) {
sm.spinwait();
__atomic_fetch_add(&shared, 1, __ATOMIC_SEQ_CST);
sm.signal();
}
} else {
for (int n = 0; n < NUM_BANGS; ++n) {
sm.spinwait();
__atomic_fetch_add(&shared, -1, __ATOMIC_SEQ_CST);
sm.signal();
}
}
printf("Worker %d done\n", worker);
return NULL;
}
int main() {
pthread_t id[NUM_TEST_THREADS]; //thread ids
// create test worker threads
for(int i = 0; i < NUM_TEST_THREADS; i++)
pthread_create(&id[i], NULL, fun, (void*)((intptr_t)(i)));
// join threads to complete their task
for(int i = 0; i < NUM_TEST_THREADS; i++)
pthread_join(id[i], NULL);
//final value of shared variable. For an odd number of
// workers this is the loop count, NUM_BANGS
printf("Test done. Final value: %d\n", shared);
const int expected = (NUM_TEST_THREADS & 1) ? NUM_BANGS : 0;
if (shared == expected) {
puts("PASS");
} else {
printf("Value expected was: %d\nFAIL\n", expected);
}
return 0;
}
I'm trying to have pthreads run multiple instances of a function at once, to increase runtime speed and efficiency. My code is supposed to spawn threads and keep them open for whenever there is more items in the queue. Then those threads are supposed to do 'something'. The code is supposed to ask to "continue?" when there are no more items in the queue, and if I type "yes", then items should be added to the queue and the threads should continue doing 'something'. This is what I have so far,
# include <iostream>
# include <string>
# include <pthread.h>
# include <queue>
using namespace std;
# define NUM_THREADS 100
int main ( );
queue<int> testQueue;
void *checkEmpty(void* arg);
void *playQueue(void* arg);
void matrix_exponential_test01 ( );
void matrix_exponential_test02 ( );
pthread_mutex_t queueLock;
pthread_cond_t queue_cv;
int main()
{
pthread_t threads[NUM_THREADS+1];
pthread_mutex_init(&queueLock, NULL);
pthread_cond_init (&queue_cv, NULL);
for( int i=0; i < NUM_THREADS; i++ )
{
pthread_create(&threads[i], NULL, playQueue, (void*)NULL);
}
string cont = "yes";
do
{
cout<<"Continue? ";
getline(cin, cont);
pthread_mutex_lock (&queueLock);
for(int z=0; z<10; z++)
{
testQueue.push(1);
}
pthread_mutex_unlock (&queueLock);
}while(cont.compare("yes"));
pthread_mutex_destroy(&queueLock);
pthread_cond_destroy(&queue_cv);
pthread_exit(NULL);
return 0;
}
void* checkEmpty(void* arg)
{
while(true)
{
pthread_mutex_lock (&queueLock);
if(!testQueue.empty()){
pthread_cond_signal(&queue_cv);}
pthread_mutex_unlock (&queueLock);
}
pthread_exit(NULL);
}
void* playQueue(void* arg)
{
while(true)
{
pthread_cond_wait(&queue_cv, &queueLock);
pthread_mutex_lock (&queueLock);
if(!testQueue.empty())
{
testQueue.pop();
cout<<testQueue.size()<<endl;
}
pthread_mutex_unlock (&queueLock);
}
pthread_exit(NULL);
}
So my issue lies with the fact that the code goes into deadlock, and I cant figure out where the issue occurs. I'm no veteran with multithreading so its very easy for me to make a mistake here. I am also running this on Windows.
You have two issues :
The condition variable queue_cv is never signaled. You can signal it with pthread_cond_signal after having pushed elements in the queue : pthread_cond_signal(&queue_cv);
In playQueue, you try to acquire the lock after returning from pthread_cond_wait : since your mutex is not reentrant, this is undefined behavior (this is likely the source of your deadlock). Just remove the pthread_mutex_lock (&queueLock);
Note:
I'm not sure what is it's true purpose, but the checkEmpty() method is never called
I am new to multithreading and hence started with a small program. The job expected from the program is, to print integers one after the other by means of two threads in such a way that one thread should print one number and the other thread should print the next number and this process should continue till a maximum number defined.
For this I wrote a small program and iam facing dead lock. I tried to find mutex owner using gdb but it;s just printing $3 = 2 when I execute print mutex command.
Here is the source code:
#include <iostream>
#include <fstream>
#include <pthread.h>
#include <signal.h>
const int MAX_NUM = 13;
pthread_cond_t cond[1] = {PTHREAD_COND_INITIALIZER,};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int Count = 0;
using namespace std;
void* thread1(void*)
{
do {
cout<<"inside thread 1 abt to acquire lock"<<endl;
// Increment counter in thread1
pthread_mutex_lock(&mutex);
cout<<"inside thread 1 blocked"<<endl;
pthread_cond_wait(&cond[0],&mutex);
cout<<"after pthread_cond_wait in thread1"<<endl;
pthread_cond_signal(&cond[1]);
if(Count < MAX_NUM)
{
Count++;
pthread_mutex_unlock(&mutex);
cout<<"Printing from thread 1"<<endl;
cout<<Count<<endl;
}
else
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
}while(1);
}
void* thread2(void*)
{
do{
cout<<"inside thread 2 abt to acquire lock"<<endl;
pthread_mutex_lock(&mutex);
cout<<"inside thread 2 blocked"<<endl;
pthread_cond_wait(&cond[1],&mutex);
// Increment counter in thread2
pthread_cond_signal(&cond[0]);
if(Count < MAX_NUM)
{
Count++;
pthread_mutex_unlock(&mutex);
cout<<"Printing from thread 2"<<endl;
cout<<Count<<endl;
}
else
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
}while(1);
}
int main()
{
pthread_t t[2];
void* (*fun[2])(void*);
fun[0]=thread1;
fun[1]=thread2;
for (int i =0 ; i < 2; ++i)
{
pthread_create(&t[i],NULL,fun[i],NULL);
}
cout<<"threads created"<<endl;
pthread_cond_signal(&cond[0]);
cout<<"In main after sending signal"<<endl;
pthread_join(t[0],NULL);
pthread_join(t[1],NULL);
pthread_exit(NULL);
}
Output is:
inside thread 1 abt to acquire lock
inside thread 1 blocked
inside thread 2 abt to acquire lock
inside thread 2 blocked
threads created
In main after sending signal
I expected main() thread to send a signal to thread 1 which does it's job (i.e. updating counter) and then passes signal to thread 2 which does it's job (i.e. updating counter) and passes signal to thread 1. This process should continue until max number is reached. If max number is reached each process unlocks mutex and exits gracefully.
Please help me. I really tried a lot nothing worked.
the line
pthread_cond_t cond[1] = {PTHREAD_COND_INITIALIZER,};
defines an array of size 1, but later on you use cond[1], the second entry in the array, which is undefined. Did you mean
pthread_cond_t cond[2] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};
This looks like an unlucky typo. (Due to the preceeding MAX_NUM = 13?)
In addition to #TooTone's observation you need to understand one aspect of how condition variables work. If you signal a condition variable when no thread is blocked on it nothing will happen. The condition variable has no memory, so if a little bit later a thread blocks on in it will stay locked until the condition is signaled again.
Your main function signals cond[0] right after it started the threads, so it is possible that the threads haven't reached their blocking point yet. Or if they are blocked then it can happen that when one thread signals the other one that other one isn't blocked. So after you fix your condition variable array you will see that the test runs a bit more, but eventually deadlocks again.
I was able to make it work using a quick & dirty trick of introducing delays before signaling the condition variables. This gives the threads time to reach their blocking points before the signaling happens. Here is the modified code:
const int MAX_NUM = 13;
pthread_cond_t cond[2] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int Count = 0;
using namespace std;
void* thread1(void*)
{
do {
cout<<"inside thread 1 abt to acquire lock"<<endl;
// Increment counter in thread1
pthread_mutex_lock(&mutex);
cout<<"inside thread 1 blocked"<<endl;
pthread_cond_wait(&cond[0],&mutex);
cout<<"after pthread_cond_wait in thread1"<<endl;
if(Count < MAX_NUM)
{
Count++;
pthread_mutex_unlock(&mutex);
cout<<"Printing from thread 1"<<endl;
cout<<Count<<endl;
usleep(1000000);
pthread_cond_signal(&cond[1]);
}
else
{
pthread_mutex_unlock(&mutex);
usleep(1000000);
pthread_cond_signal(&cond[1]);
pthread_exit(NULL);
}
}while(1);
}
void* thread2(void*)
{
do{
cout<<"inside thread 2 abt to acquire lock"<<endl;
pthread_mutex_lock(&mutex);
cout<<"inside thread 2 blocked"<<endl;
pthread_cond_wait(&cond[1],&mutex);
// Increment counter in thread2
if(Count < MAX_NUM)
{
Count++;
pthread_mutex_unlock(&mutex);
cout<<"Printing from thread 2"<<endl;
cout<<Count<<endl;
usleep(1000000);
pthread_cond_signal(&cond[0]);
}
else
{
pthread_mutex_unlock(&mutex);
usleep(1000000);
pthread_cond_signal(&cond[0]);
pthread_exit(NULL);
}
}while(1);
}
int main()
{
pthread_t t[2];
void* (*fun[2])(void*);
fun[0]=thread1;
fun[1]=thread2;
for (int i =0 ; i < 2; ++i)
{
pthread_create(&t[i],NULL,fun[i],NULL);
}
cout<<"threads created"<<endl;
usleep(1000000);
pthread_cond_signal(&cond[0]);
cout<<"In main after sending signal"<<endl;
pthread_join(t[0],NULL);
pthread_join(t[1],NULL);
pthread_exit(NULL);
}
Using condition variables for this kind of thing isn't the best idea. Semaphores are better suited to the task because those do have memory and remember their signaled state even if nobody is waiting on them when they are signaled.
The main() function creates a thread that is supposed to live until the user wishes to exit the program. The thread needs to return values to the main functions at periodic intervals. I tried doing something like this, but hasn't worked well -
std::queue<std::string> q;
void start_thread(int num)
{
std::string str;
//Do some processing
q.push(str);
}
int main()
{
//Thread initialization
int i;
//Start thread
pthread_create(&m_thread,NULL,start_thread,static_cast<void *>i);
while(true)
{
if(q.front())
{
std::cout<<q.front();
return 0;
}
}
//Destroy thread.....
return 0;
}
Any suggestions?
It is not safe to read and write from STL containers concurrently. You need a lock to synchronize access (see pthread_mutex_t).
Your thread pushes a single value into the queue. You seem to be expecting periodic values, so you'll want to modify start_thread to include a loop that calls queue.push.
The return 0; in the consumer loop will exit main() when it finds a value in the queue. You'll always read a single value and exit your program. You should remove that return.
Using if (q.front()) is not the way to test if your queue has values (front assumes at least one element exists). Try if (!q.empty()).
Your while(true) loop is gonna spin your processor somethin' nasty. You should look at condition variables to wait for values in the queue in a nice manner.
try locking a mutex before calling push() / front() on the queue.
Here is a working example of what it looks like you were trying to accomplish:
#include <iostream>
#include <queue>
#include <vector>
#include <semaphore.h>
#include <pthread.h>
struct ThreadData
{
sem_t sem;
pthread_mutex_t mut;
std::queue<std::string> q;
};
void *start_thread(void *num)
{
ThreadData *td = reinterpret_cast<ThreadData *>(num);
std::vector<std::string> v;
std::vector<std::string>::iterator i;
// create some data
v.push_back("one");
v.push_back("two");
v.push_back("three");
v.push_back("four");
i = v.begin();
// pump strings out until no more data
while (i != v.end())
{
// lock the resource and put string in the queue
pthread_mutex_lock(&td->mut);
td->q.push(*i);
pthread_mutex_unlock(&td->mut);
// signal activity
sem_post(&td->sem);
sleep(1);
++i;
}
// signal activity
sem_post(&td->sem);
}
int main()
{
bool exitFlag = false;
pthread_t m_thread;
ThreadData td;
// initialize semaphore to empty
sem_init(&td.sem, 0, 0);
// initialize mutex
pthread_mutex_init(&td.mut, NULL);
//Start thread
if (pthread_create(&m_thread, NULL, start_thread, static_cast<void *>(&td)) != 0)
{
exitFlag = true;
}
while (!exitFlag)
{
if (sem_wait(&td.sem) == 0)
{
pthread_mutex_lock(&td.mut);
if (td.q.empty())
{
exitFlag = true;
}
else
{
std::cout << td.q.front() << std::endl;
td.q.pop();
}
pthread_mutex_unlock(&td.mut);
}
else
{
// something bad happened
exitFlag = true;
}
}
return 0;
}