It seems to be platform related (works with Ubuntu 12.04 on my laptop, doesn't work with another Ubuntu 12.04 on my workstation).
This is a sample code about what I am doing with two threads.
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <GL/glfw.h>
using namespace std;
int main() {
atomic_bool g_run(true);
string s;
thread t([&]() {
cout << "init" << endl;
if (!glfwInit()) {
cerr << "Failed to initialize GLFW." << endl;
abort();
}
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2);
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);
if(!glfwOpenWindow(640, 480, 8, 8, 8, 0, 24, 0, GLFW_WINDOW)) {
glfwTerminate();
cerr << "Cannot open OpenGL 2.1 render context." << endl;
abort();
}
cout << "inited" << endl;
while (g_run) {
// rendering something
cout << "render" << endl;
this_thread::sleep_for(chrono::seconds(1));
}
// unload glfw
glfwTerminate();
cout << "quit" << endl;
});
__sync_synchronize(); // a barrier added as ildjarn suggested.
while (g_run) {
cin >> s;
cout << "user input: " << s << endl;
if (s == "q") {
g_run = false;
cout << "user interrupt" << endl;
cout.flush();
}
}
__sync_synchronize(); // another barrier
t.join();
}
Here is my compile parameters:
g++ -std=c++0x -o main main.cc -lpthread -lglfw
My laptop run this program, like this:
init
inited
render
render
q
user input: q
user interrupt
quit
And workstation just outputs:
init
inited
render
render
q
render
q
render
q
render
^C
It just simply ignored my inputs (another program same procedure with glew and glfw, just jump out of the while loop in main thread, without reading my inputs.) BUT this thing works normally with gdb!
any idea of what's going on?
Update
After more tests on other machines, NVIDIA's driver caused this. Same thing happens on other machines with NVIDIA graphics card.
g_run
astd::atomic<bool>
rather than a plainbool
. – Cosecantuser interrupt
in your second output. Can you add more debug logs aftercin >> s;
? It's not clear now - your main thread does not receive CPU ticks orif (s == "q")
does not work for some reason. – Shu-pthread
option during linking? – Shuglfw
library on your workstation. – Shustd::atomic_bool
impose a memory barrier? My understanding is that it should havememory_order::memory_order_seq_cst
characteristics, which implies a full memory barrier on accesses. – Kalongbool
(which is what the OP had originally; it's since been edited). – Cosecant