Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

linux - Accessing global variables in pthreads in different c-files

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 variable (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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...