0

I made a very small program that creates two threads:

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

void *start()
{
        printf("Am a new thread!\n");
        printf("%d\n",pthread_self());
}

void main()
{

        pthread_t thread_id1;
        pthread_t thread_id2;

        pthread_create(&thread_id1,NULL,start,NULL);
        pthread_create(&thread_id2,NULL,start,NULL);
        //pthread_join(thread_id,NULL);
        sleep(30);

}

When I compile and run the program with:

gcc create.c -lpthread
./a.out

And I open a new terminal and try to view the threads, this is what I get:

ps -efL | grep a.out
root      1943 20158  1943  0    1 15:25 pts/4    00:00:00 ./a.out
root      1985  1889  1985  0    1 15:25 pts/5    00:00:00 grep --color=auto a.out

So why can't I see two thread ids here?

1 Answer 1

0

The two additional threads write their message and terminate, so you don't have the time to see them with ps.

from man pthread_create:

The new thread terminates in one of the following ways:

* It calls pthread_exit(3), specifying an exit status value that is available to another thread in the same process that calls pthread_join(3).

* It returns from start_routine(). This is equivalent to calling pthread_exit(3) with the value supplied in the return statement.

[...]

You can follow what's going on for example with strace:

$ strace -f -e trace=clone,exit ./a.out 
clone(strace: Process 409 attached
child_stack=0x7f7126930ff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f71269319d0, tls=0x7f7126931700, child_tidptr=0x7f71269319d0) = 409
[pid   408] clone(strace: Process 410 attached
child_stack=0x7f712612fff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f71261309d0, tls=0x7f7126130700, child_tidptr=0x7f71261309d0) = 410
Am a new thread!
Am a new thread!
647173888
638781184
[pid   409] exit(0 <unfinished ...>
[pid   410] exit(0 <unfinished ...>
[pid   409] <... exit resumed>)         = ?
[pid   410] <... exit resumed>)         = ?
[pid   410] +++ exited with 0 +++
[pid   409] +++ exited with 0 +++

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .