I have a global variable declared in a common header file that I want multiple threads to have access too. However if main.cpp changes the global variable before the thread is created or after it created, the change isn't shown in any of the spawn threads. In this case it won't show the value 5 in run_thread1. I thought static variables were shared by all threads by default.
Why am I getting this behavior and how do I fix it so that I have a global variable shared among threads?
main.cpp
#include <iostream>
#include <pthread.h>
#include "../include/common.hpp"
#include "../include/thread1.hpp"
int main() {
pthread_t thread1;
g_var = 5;
std::cout << "main: g_var = " << g_var << std::endl;
int rc = pthread_create(&thread1,
NULL,
run_thread1,
(void *) 0);
return 0;
}
thread1.hpp
#ifndef THREAD1
#define THREAD1
#include <iostream>
#include "common.hpp"
void run_thread1(void* p);
#endif
thread1.cpp
#include "../include/thread1.hpp"
void run_thread1(void* p) {
std::cout << "Thread1: g_var = " << g_var << std::endl;
return;
}
common.hpp
#ifndef COMMON
#define COMMON
static int g_var;
#endif
CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(pthreads)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fpermissive")
set(SRC ${CMAKE_CURRENT_SOURCE_DIR}/src)
file(GLOB SRCS ${SRC}/*.cpp)
set_source_files_properties(${SRCS} PROPERTIES LANGUAGE CXX )
include_directories("include/")
add_executable(pthreads ${SRCS})
output:
main: g_var = 5
Thread1: g_var = 0