Linux has a unique way of implementing threads: For the Linux kernel, there is no concept of
Question:
Linux has a unique way of implementing threads: For the Linux kernel, there is no concept of a thread. Instead, there are processes that may, or may not share resources with other processes. This approach differs greatly with operating systems such as Sun Solaris or Microsoft Windows, which have explicit support for threads.
1. Creating "threads" in Linux
“Threads” are created like normal processes, with the exception that the arguments to the clone() system call will indicate that some resources will be shared (not duplicated) between the parent and the child.
A new “thread” has the same parent process as the caller of clone(). After all of the threads in a thread group terminate, the parent process of the thread group is sent a termination signal.
- Modify the program as shown below. Additions are in bold.
//thread.c v2 #include #include #include #define _SCHED_H 1 #define __USE_GNU 1 #include #define STACK_SIZE 4096 int var1 = 0;//global variable int var2 = 0;//global variable int thread_behavior(void *arg) { printf("\t\tThread: Inside thread_behavior, my pid: %d", getpid()); var2++; printf("\t\tThread: var2 = %d", var2); sleep(1);//sleep 1 second printf("\t\tThread: Terminating thread_behavior..."); return 0; } int child_behavior() { int state; printf("Child: Inside child_behavior, my pid: %d", getpid()); var1++; printf("Child: var1 = %d", var1); //reserve some space for the thread's stack //no need to reserve space for data or code, // since thread will share its creator's data and code section void *thread_stack = malloc(STACK_SIZE); int thread_pid; printf("Child: Creating new thread and waiting..."); //clone system call thread_pid = clone(&thread_behavior, thread_stack + STACK_SIZE, CLONE_SIGHAND | CLONE_FS |CLONE_VM | CLONE_FILES | CLONE_THREAD, NULL); sleep(1);//sleep 1 second printf("Child: var2 = %d", var2); printf("Child: Terminating child_behavior..."); return 0; } int main() { int state; int child_pid; printf("\tParent: my pid: %d", getpid()); printf("\tParent: Creating new child and waiting..."); //clone system call child_pid = fork(); //duplicate if( child_pid == 0 ){ //child: The return of fork() is zero child_behavior(); } else { wait(&state);//wait for the child to terminate printf("\tParent: Done waiting! Child pid: %d", child_pid); printf("\tParent: var1 = %d", var1); } return 0; } |
What is the output of this program? Note the values for the pids. Explain the value(s) obtained for var2.
Smith and Roberson Business Law
ISBN: 978-0538473637
15th Edition
Authors: Richard A. Mann, Barry S. Roberts