开发者

Accessing global variables in pthreads in different c-files

开发者 https://www.devze.com 2023-04-03 23:17 出处:网络
I have a main.c with a global variable called int countboards. In the main() I start apthread, that listens to ONE TCP-Connection and runs that through (progserver.c). Means, this thread will never re

I have a main.c with a global variable called int countboards. In the main() I start a pthread, that listens to ONE TCP-Connection and runs that through (progserver.c). Means, this thread will never return. In the main() I enter the function rmmain(...) which is in the rm.c (RM=Ressource Manager). In rm.c I read countboards, in the progserver.c in the pthread I write to this var开发者_开发技巧iable (both are made accessible by extern int countboards).

So the problem is, when I write to countboards in the pthread and I want to access this variable after it's been written to in the rm.c, it still has the old value (in this case 0 instead of for example 10). Why?

main.c:

int countboards;

int main(int argc, char** argv) {
  countboards = 0;
  pthread_t thread;
  pthread_create(&thread, NULL, startProgramserver, NULL);

  rmmain();

  return 0;
}

rm.c:

extern int countboards;

int rmmain(vhbuser* vhbuserlist, int countvhbuser,
       userio* useriolist, int countios, int usertorm, int rmtosslserver, int sslservertorm) {
  while(1) {
    int n;
    n=read(usertorm,buf,bufc); // blocks until command comes from the user
    ...
    board* b = findAFreeBoard(boardlist, countboards, usagelist); // here countboards should be >0, but it isn't
    ...
  }
}

programserver.c:

extern int countboards;
void* startProgramserver(void*) {
  ...
  sock = tcp_listen();
  ...
  http_serve(ssl,s, sslpipes);
}

static int http_serve(SSL *ssl, int s, void* sslpipes) {
  ...
  countboards = countboards + countboardscommands;
  ...
  // here countboards has the new value
}


You're seeing a cached copy in each thread. I would suggest declaring it volatile int countboards except that's really not a good way to go about things.

Globals are kinda evil. You'd be better served by passing a pointer to each thread and synchronizing with a mutex.

Edit: To expand on this since I was in a hurry last night ...

http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/

As KasigiYabu mentions in the comments below, creating a "context" structure that contains all the information you want to share between the threads and passing that in to pthread_create as the last arg is a sound approach and is what I do as well in most cases.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号