UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2007-11-26 11:33 PM

darthsidious
Member
Registered: 2007-11-18
Posts: 14

Re: Thread and Global Variable value

hello, something is happening and it's driving me nuts.

i've a global variable like this:

int iPlayerOnline;

inside main(), when the player starts playing, y modify that variable and set it to iPlayerOnline = 1;
Later, i start a thread (posix) with the know pthread_create(...);

inside that thread i try to verify that value with an if statement like this

if(iPlayerOnline==1)
  {
   ...do some stuff
  }

but the problem is that that value is never 1, it's always 0. it never takes the value i've assigned in main(). I've read one by one every single line of the code and I NEVER assign anything to iPlayerOnline but in main when i do iPlayerOnline=1; Never 0.

what could be happening? it has never happened to me before, it's the strangest thing i've ever seen.

thanks!!!

Offline

#2 2007-11-27 01:18 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Thread and Global Variable value

It might be optimised away. It might be a bug in your code. You might go crazy. Or the bedbugs were hungry again. Hard to say without seeing your code, won't you think?

If you're desperate you could run it through a debugger and set a breakpoint on each iPlayerOnline access. Or something.

Offline

#3 2007-11-27 05:44 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: Thread and Global Variable value

You might try declaring the variable volatile, like this:

volatile int iPlayerOnline = 0;

That way the optimizer will "know" that it is being accessed by multiple threads and won't try any clever tricks with it. 

-Jeremy

Offline

#4 2007-12-03 01:10 PM

darthsidious
Member
Registered: 2007-11-18
Posts: 14

Re: Thread and Global Variable value

hello, i solved it by declaring that variable like static.
I don't know why but i read somewhere that global variables are not thread-safe so i put it like static and everthing worked fine.

thanks!!!

Offline

#5 2007-12-03 05:07 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: Thread and Global Variable value

Offline

Board footer

Powered by FluxBB