Infinite
Infinite

Reputation: 3428

when pthread_once encounters reentrancy

What would happen in the situation below?

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

static pthread_once_t random_is_initialized = PTHREAD_ONCE_INIT;
void initialize(){
 foo("init()");
}


int foo(char *str)
{
    pthread_once(&random_is_initialized, initialize);
    printf("%s", str);
}

int main(){
    foo("main");
}

Will it cause infinite recursion? Thanks!

[edit] I ran the code. It seems the code does not cause infinite recursion, but it blocks at the second pthread_once that I have to "ctrl + c". That is, deadlock happened.

(gdb) bt
#0  0x0012d422 in __kernel_vsyscall ()
#1  0x00139404 in pthread_once () from /lib/tls/i686/cmov/libpthread.so.0
#2  0x080484a3 in foo (str=0x8048590 "init()") at main.c:12
#3  0x08048486 in initialize () at main.c:6
#4  0x00139430 in pthread_once () from /lib/tls/i686/cmov/libpthread.so.0
#5  0x080484a3 in foo (str=0x804859a "main") at main.c:12
#6  0x080484ce in main () at main.c:17

Upvotes: 0

Views: 368

Answers (1)

Variable Length Coder
Variable Length Coder

Reputation: 8116

On a proper pthread implementation init_routine() will only be called once so there will be no infinite recursion. However, all other callers to pthread_once() must wait until init_routine() has finished executing. In this case it will never finish so you've created a deadlock.

Upvotes: 1

Related Questions