线程之间不共享静态全局变量

时间:2016-10-14 06:35:27

标签: c++ multithreading static pthreads global

我在一个公共头文件中声明了一个全局变量,我希望多个线程也可以访问它。但是,如果main.cpp在创建线程之前或创建线程之后更改全局变量,则更改不会显示在任何生成线程中。在这种情况下,它不会在run_thread1中显示值5。我认为默认情况下所有线程都共享静态变量。

为什么我会遇到这种行为?如何修复它以便我在线程之间共享一个全局变量?

的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})

输出:

  

main:g_var = 5

     

Thread1:g_var = 0

0 个答案:

没有答案