Accessing global variables in pthreads in different c-files

后端 未结 1 665
攒了一身酷
攒了一身酷 2020-12-11 10:32

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 (progs

相关标签:
1条回答
  • 2020-12-11 11:32

    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 讨论(0)
提交回复
热议问题