Can't understand the behavior of pthread_create () in the following program?

#include <stdio.h>
#include <pthread.h>

void *thread_func(void *arg)
{
        printf("hello, world \n");
        return 0;
}

int main(void)
{
        pthread_t t1, t2;

        pthread_create(&t1, NULL, thread_func, NULL);
        pthread_create(&t2, NULL, thread_func, NULL);

        printf("t1 = %d\n",t1);
        printf("t2 = %d\n",t2);

        return 0;
}

The above program creates two threads, where each thread prints "Hello World".

So, according to my understanding, "Hello world" should print a maximum of 2 times.

However, when running the same program several times (back to back), there are scripts in which "Hello world" is printed more than 2 times. So I don’t understand how it prints an unexpected number of times?

The following is the output:

[rr@ar ~]$ ./a.out
t1 = 1290651392
t2 = 1282258688
hello, world
hello, world


[rr@ar ~]$ ./a.out
t1 = 1530119936
t2 = 1521727232
hello, world
hello, world
hello, world

, ", " 3 . -, , , 3 ?

+4
3

. Linux 16.04, , 3 hello world , . , , main , , . - :

t1=xxxx
t2=yyyy
he

, main , stdout. , main exit, stdio.

, , 3 , , , main , . printf, . () :

  • thread1 , .
  • , , hello world
  • thread1 hello world
  • thread2 hello world
  • main .

printf , , (, ). , , , , concurrency ..

(3 ), , main/ . , concurrency ( ...).

+3

, , . , ( , ), printf() , ( - pthread_<something>), , , printf(3) write(2) .

  • Thread A ( , , Thread A ) printf(), "Hello, world\n" write(2) it, , tty, \n .
  • Thread B printf(2) ( "Hello, world\n"), syscall write(2) ( ) . "Hello, world\n" .
  • Thread A, write(2) ( write(2) inode --- ) flushes it view (, , ) ( "Hello, world\n") "Hellow, world\n" )

: "Hellow, world\n" .

, , printf, , ( ), write(2) ( , write(2) , )

+1

, .

, . " " , .

, , . " ".

, 3 . , , . : , : RUN1: , , " ", RUN1 main . RUN2. , .

, :

t1=346236763               (RUN1 - main)
t2=876237623               (RUN1 - main)
hello, world               (RUN1 - subthread)
hello, world               (RUN1 - subthread)
hello, world               (RUN2 - subthread)
hello, world               (RUN2 - subthread)
t1=3786768623              (RUN2 - main)
t2=7843473478              (RUN2 - main)

, 4 " ", .

0

Source: https://habr.com/ru/post/1678220/


All Articles