멀티 스레드 동기화 메커니즘

1 스핀

짧은 대기의 경우, 짧은 수면의 종류를받을 자격이 없어.

  JMP 11B
 12 :
 GET_LOCK : 
    잠금  BTS $ 0 , 0x6000
     JC GET_LOCK의
   잠금 smp_cpus incw
   MOV $ smp_cpus %의 BX의
   잠금  BTR $ 0 , 0x6000 / * 박리 잠금 * /
   MOV  0 (%의 BX)를 % SI 

  ... 

smp_ap_boot_code_end :

이 때문에 상이한 위치 "포인트"화면에 관해서는, 각각의 핵의 시작 자체 핵이 smp_cpus 따라 번호가 매겨 수득하고, 그 다음 루프는 ASCII 코드를 증가시킨다.

 

2, 된 atomic_t

이것은 원자 리눅스 커널의 수이고, 대응 atomic_inc / DEC () 일련의 방법이있다.

86 일, 구현은 내부 잠금 명령 접두어에 의존하고 있습니다.

 

3, 세마포어

() sem_init; sem_wait (); sem_post (); () sem_destroy;

포크 할 ()를 계속 사용하는 경우, 사용할 필요가 메모리 영역을 공유했습니다.

또한 각 게시물 후에 만 ​​큐 과정에서 일어날 수 있습니다. sem_wait는 (), 그들은 자연스럽게) (sem_post 호출 입력 할 수 있기 때문에 확인을 기다리는 프로세스의 큐는 "다음."라고되어 있기 때문에

SO에 특히 좋은 :

https://stackoverflow.com/questions/16400820/how-to-use-posix-semaphores-on-forked-processes-in-c

 

어떻게 C에서 갈래의 프로세스에 POSIX 세마포어를 사용 하는가?

나는 여러 프로세스를 포크 한 다음에 세마포어를 사용하고 싶습니다. 여기에 내가 뭘하려 :

sem_init(&sem, 1, 1); /* semaphore*, pshared, value */ . . . if(pid != 0){ /* parent process */ wait(NULL); /* wait all child processes */ printf("\nParent: All children have exited.\n"); . . /* cleanup semaphores */ sem_destroy(&sem); exit(0); } else{ /* child process */ sem_wait(&sem); /* P operation */ printf(" Child(%d) is in critical section.\n",i); sleep(1); *p += i%3; /* increment *p by 0, 1 or 2 based on i */ printf(" Child(%d) new value of *p=%d.\n",i,*p); sem_post(&sem); /* V operation */ exit(0); }
.....

 
높은 찬양 대답 :

당신이 직면하고있는 문제의 오해 sem_init()기능. 당신이 읽을 때 매뉴얼 페이지를 이 표시됩니다

pshared가 인수 세마포어는 프로세스의 스레드 사이, 또는 프로세스간에 공유 될 것인지 여부를 나타낸다.

이 시점까지 다 읽은 경우 pshared가의 아닌 값은 세마포어 프로세스 간 세마포어를 만들 것이라고 생각합니다. 그러나 이것은 잘못된 것입니다. 당신은 독서를 계속해야 당신은 당신이 공유 메모리 영역에 세마포어를 찾을 필요가 있음을 이해하게 될 것입니다. 이를 위해 몇 가지 기능은 아래 볼 수 있습니다로 사용할 수 있습니다 :

pshared가 0이 아닌 경우, 세마포어는 프로세스들 사이에서 공유되고, 공유 메모리 영역에 위치한다 ((shm_open 3 참조)의 mmap (2)하는 shmget (2)). (이후 포크 (2 만든 자식) 상속 부모의 메모리 맵핑은 또한 세마포어에 액세스 할 수있다.) (3) sem_post 사용 세마포어에서 작동 할 수있는 공유 기억 영역을 액세스 할 수있는 모든 과정 sem_wait (3) 등 .

그래서 저는 제가 사용하는 사람들을 격려하고자, 다른 사람보다 더 복잡한 방법으로이 방법을 찾을 sem_open()대신 sem_init().

당신이 완전한 프로그램을 볼 수 있습니다 아래의 다음을 보여

  • 어떻게 공유 메모리를 할당하고 갈래 프로세스간에 공유 변수를 사용합니다.
  • 어떻게 공유 메모리 영역에 세마포어를 초기화하고 여러 프로세스에 의해 사용된다.
  • 어떻게 여러 프로세스를 포크와 자식 출구의 모든 때까지 부모 대기를 확인합니다.
#include <stdio.h>          /* printf() */ #include <stdlib.h> /* exit(), malloc(), free() */ #include <sys/types.h> /* key_t, sem_t, pid_t */ #include <sys/shm.h> /* shmat(), IPC_RMID */ #include <errno.h> /* errno, ECHILD */ #include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */ #include <fcntl.h> /* O_CREAT, O_EXEC */ int main (int argc, char **argv){ int i; /* loop variables */ key_t shmkey; /* shared memory key */ int shmid; /* shared memory id */ sem_t *sem; /* synch semaphore *//*shared */ pid_t pid; /* fork pid */ int *p; /* shared variable *//*shared */ unsigned int n; /* fork count */ unsigned int value; /* semaphore value */ /* initialize a shared variable in shared memory */ shmkey = ftok ("/dev/null", 5); /* valid directory name and a number */ printf ("shmkey for p = %d\n", shmkey); shmid = shmget (shmkey, sizeof (int), 0644 | IPC_CREAT); if (shmid < 0){ /* shared memory error check */ perror ("shmget\n"); exit (1); } p = (int *) shmat (shmid, NULL, 0); /* attach p to shared memory */ *p = 0; printf ("p=%d is allocated in shared memory.\n\n", *p); /********************************************************/ printf ("How many children do you want to fork?\n"); printf ("Fork count: "); scanf ("%u", &n); printf ("What do you want the semaphore value to be?\n"); printf ("Semaphore value: "); scanf ("%u", &value); /* initialize semaphores for shared processes */ sem = sem_open ("pSem", O_CREAT | O_EXCL, 0644, value); /* name of semaphore is "pSem", semaphore is reached using this name */ printf ("semaphores initialized.\n\n"); /* fork child processes */ for (i = 0; i < n; i++){ pid = fork (); if (pid < 0) { /* check for error */ sem_unlink ("pSem"); sem_close(sem); /* unlink prevents the semaphore existing forever */ /* if a crash occurs during the execution */ printf ("Fork error.\n");  } else if (pid == 0) break; /* child processes */ } /******************************************************/ /****************** PARENT PROCESS ****************/ /******************************************************/ if (pid != 0){ /* wait for all children to exit */ while (pid = waitpid (-1, NULL, 0)){ if (errno == ECHILD) break; } printf ("\nParent: All children have exited.\n"); /* shared memory detach */ shmdt (p); shmctl (shmid, IPC_RMID, 0); /* cleanup semaphores */ sem_unlink ("pSem"); sem_close(sem); /* unlink prevents the semaphore existing forever */ /* if a crash occurs during the execution */ exit (0); } /******************************************************/ /****************** CHILD PROCESS *****************/ /******************************************************/ else{ sem_wait (sem); /* P operation */ printf (" Child(%d) is in critical section.\n", i); sleep (1); *p += i % 3; /* increment *p by 0, 1 or 2 based on i */ printf (" Child(%d) new value of *p=%d.\n", i, *p); sem_post (sem); /* V operation */ exit (0); } }
 

또한 sem_open () 함수에 대한 우려.

추천

출처www.cnblogs.com/xiang-yin/p/12114209.html