"thread fork" in C (ideally POSIX, but only Linux works)

Are there any / pthread wrappers / library arguments clonethat will allow me to have tforksomething that, like fork(), allows me to continue executing the code in context, rather than pointing to a new function to execute in a new thread.

If not, is there an easy way to write this myself?


Usage would be ideally the same as fork, but the value would be threadlike, like a far-fetched example:

int main() {
        int ival = 0;
        if(tfork() == 0) {
                sleep(10);
                ival = 5;
                _exit(); // or exit or return or whatever
        } else {
                while(1) {
                        printf("ival=%d\n", ival);
                        if(ival != 0) {
                                printf("ival changed. done.\n");
                                return 0;
                        }
                        sleep(1);
                }
        }
}

Must output:

ival=0
ival=0
ival=0
ival=0
ival=0
ival=0
ival=0
ival=0
ival=0
ival=0
ival=5
ival changed. done.
+3
source share
4 answers

, . (, fork()) , .

, , .

- .

+5

- openMP

, , .

+1

Uh, , vfork() Linux, ( , ).

, (snd ), vfork() , , execve() _exit() ( , exit() vfork()).

, vfork() , exec*() _exit(). , vfork() Linux, .

So, as you can see, there are many restrictions on what you can do when sharing memory and returning la fork(): there is a very good reason why thread creation is usually done by calling a function .

+1
source

On Linux, fork () and pthread_create () are just a wrapper over clone (). You yourself call clone () directly to get the desired effect. For example (not actual code, but very close):

pid = syscall(SYS_clone, (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_PARENT), NULL, NULL, NULL );

if(-1 == pid) { 
    return -1;
}

if(pid) {
          return pid;
    } else {

     // Your new thread code goes here
   }

More details here: http://linux.die.net/man/2/clone

+1
source

All Articles