First time poster and new to Linux multi-threaded programming. I have a multi-threaded Linux application that sends commands to a remote micro-controller and waits for responses. The application appears to be deadlocked waiting for a std::queue to be not empty. I have reduced this to a simple example for the community to comment...
I create a simple "threading" class as follows...
#include <iostream>
#include <thread>
#include <queue>
class threading {
public:
std::thread t;
std::queue<std::string> localq;
threading(std::queue<std::string> &q){
localq = q;
}
void vStartThread(void){
t = std::thread(&threading::thread_function,this); // t starts running
}
void vJoinThread(void){
t.join();
}
void thread_function(void){
std::cout << "Thread started..." << std::endl;
while(localq.empty()){
std::this_thread::yield();
}
std::cout << "This is from thread-land. This Thread has queue " << localq.front() << std::endl;
}
};
My main function is as follows...
#include <iostream>
#include <thread>
#include <queue>
#include "threading.hpp"
using namespace std;
int main()
{
//create a queue of strings
std::queue<string> strq;
//instantiate thread class - passing a reference to the previous queue...
threading thread(std::ref(strq));
thread.vStartThread();
//put a string in the queue
strq.push("Response message");
std::cout << "main thread\n";
thread.vJoinThread();
return 0;
}
I compile with...
g++ main.cpp -o main -std=c++17 -pthread
my output is...
richard@richard-Precision-5750:~/rrmdev/queue$ ./main
main thread
Thread started...
From the output of the program it seems that the queue should have had the string pushed such that the thread would have a non-empty queue. If not, I use the std::this_thread::yield() call to allow both threads to run to completion. This is not the case from the output which never finds anything in the queue. What am I doing wrong?