Thread介紹

1,315 views

Published on

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,315
On SlideShare
0
From Embeds
0
Number of Embeds
199
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Thread介紹

  1. 1. Pthread vs Fork Jack. 2007/11/13
  2. 2. Fork <stdio.h>  #include #include <stdlib.h> #include <unistd.h>  void main(void){ pid_t pid; printf(quot;hellonquot;); pid = fork(); switch (pid) { case -1: printf(quot;failure!nquot;); break; case 0: printf(quot;I am child!nquot;); break; default: printf(quot;my child is %dnquot;,pid); break; } for (;;) { /* do something here */ } } [root@jackserver ~]# gcc fork.c 
  3. 3. Pthread_Create #include <pthread.h>  #include <stdio.h>  #define MSG( msg ) {  while(1){  printf(quot;I'm %snquot;, msg);  sleep(1);  }  }  void *child( void* arg){ MSG(quot;childquot;); }  int main(){  pthread_t t;  pthread_create( &t , NULL, &child, NULL );  while(1){  printf(quot;I'm %snquot;, quot;Fatherquot;);  sleep(3);  }  }  [root@jackserver ~]# gcc pthread.c -lpthread 
  4. 4. [root@jackserver ~]# man pthread_create PTHREAD_CREATE(P) POSIX Programmer’s Manual  NAME  pthread_create - thread creation  SYNOPSIS  #include <pthread.h>  int pthread_create(pthread_t *restrict thread,  const pthread_attr_t *restrict attr,  void *(*start_routine)(void*), void *restrict arg);  DESCRIPTION  The pthread_create() function shall create a new thread, with  attributes specified by attr, within a process. If attr is NULL, the …….. 
  5. 5. [root@jackserver ~]# man fork FORK(2) Linux Programmer’s Manual FORK(2) NAME fork - create a child process SYNOPSIS #include <sys/types.h> #include <unistd.h> pid_t fork(void); DESCRIPTION fork() creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited. Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent’s page tables, and to create a unique task structure for the child. RETURN VALUE On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of execution. On failure, a -1 will be returned in the parent’s context, no child process will be created, and errno will be set appropriately.

×