[Linux] [C / C ++] Operation check memo of fork, thread and thread local variables

A note on the relationship between forks, threads and thread-local variables

fork and thread_local


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <thread>

static __thread int val = 0;

int main()
{
	int p_id;
	int status;
	int return_code = 0;

	printf("%d :Parent process start val= %d\n", getpid(), val);

	val = 1000;

	auto th = std::thread([]{
			printf("%d :thread start val= %d\n", getpid(), val);
			val = 100;
			printf("%d :thread end val= %d\n", getpid(), val);
			});

	if ((p_id = fork()) == 0) {
		/*Child process*/
		printf("%d :Child process start val= %d\n", getpid(), val);
		sleep(1);
		val = 200;
		printf("%d :End child process val= %d\n", getpid(), val);
	} else {
		/*Parent process*/
		if (p_id == -1) {
			exit(EXIT_FAILURE);
		}

		wait(&status);
		printf("%d :Parent process termination val= %d\n", getpid(), val);
	}

	th.join();

	return 0;
}

Build and execution results


$ g++ -std=c++11 fork_and_threadlocal.cpp -pthread
$ ./a.out
11217 :Parent process start val= 0
11217 :thread start val= 0       //The initial value is 0 instead of 1000
11217 :thread end val= 100
11219 :Child process start val= 1000  //Copy the value in the parent process as it is when forking(Or still shared by COW?)Has been
11219 :End child process val= 200
11217 :Parent process termination val= 1000  //Unaffected by changes in child processes

The thread_local variable did not go to its initial state (0 this time), which is not surprising due to the specifications of fork. However, it seems that exec * is usually called after fork, so it may not be relevant when actually using it.

reference

Man page of FORK fork - Wikipedia [Technical chat-Process creation and cleanup (Linux C ++)-Tsubasa's HomePage](http://www.himajin2001.com/fswiki/wiki.cgi?page=%B5%BB%BD%D1%C5% AA% BB% A8% C3% CC-% A5% D7% A5% ED% A5% BB% A5% B9% A4% CE% C0% B8% C0% AE% A4% C8% B8% E5% BB% CF % CB% F6 (Linux% 20C% 2B% 2B% CA% D4)) Cost associated with multithreaded context switching --naoya's Hatena Diary

Recommended Posts

[Linux] [C / C ++] Operation check memo of fork, thread and thread local variables
Global and local variables 2
Global and local variables 1
Check the type and version of your Linux distribution
Check the scope of local variables with the Python locals function.
Commands and files to check the version of CentOS Linux
Django installation and operation check
Declaration of C global variables
[Linux] [C / C ++] Get tid (thread id) / Wrap pthread_create to get tid of child thread
Basic knowledge of Linux and basic commands
[Python] Operation memo of pandas DataFrame
[Linux] File and directory operation commands
Operation memo of Conda virtual environment
Paiza Skill Check List of Frequently Used D and C Ranks ~ Python ~