logo

C에서의 멀티스레딩

소개:

C에서는 용어 '멀티스레딩' 수많은 사용법을 설명합니다. 스레드 동시에. 각 스레드는 다음을 수행합니다. 다른 작업 . 멀티스레딩의 동시성 특성으로 인해 많은 작업이 동시에 수행될 수 있습니다. 추가적으로, 멀티스레딩 감소시킨다 CPU의 리소스 사용량 . 멀티태스킹에는 두 가지 범주가 있습니다. 프로세스 기반 그리고 스레드 기반 . 멀티스레딩으로 설명되는 것은 적어도 두 개 이상의 스레드가 동일한 프로세스에서 동시에 실행되고 있음을 의미합니다. C에서 멀티스레딩을 이해하려면 먼저 스레드와 프로세스가 무엇인지 이해해야 합니다. 더 나은 이해를 위해 이러한 주제를 살펴보겠습니다.

Verilog 사례 설명

프로세스와 스레드란 무엇입니까?

기본 건물 차단하다 모든 프로세스의 실행. 프로그램은 여러 프로세스로 구성되며, 각 프로세스는 훨씬 더 기본적인 단위인 스레드로 구성됩니다. 따라서 스레드는 프로세스의 기본 구성 요소 또는 CPU 사용률을 공동으로 결정하는 더 간단한 단위로 간주될 수 있습니다.

스레드에는 다음 항목이 포함됩니다.

스레드 ID:

그것은 특별하다 스레드 ID 이는 스레드 형성 시 생성되고 특정 스레드 기간 동안 유지됩니다.

프로그램 카운터:

이는 다음과 같은 가치가 있습니다. 하드웨어 부하 .

등록된 세트:

의 모음입니다 공통 레지스터 .

스택:

그 잔재입니다 특정 스레드 .

또한 두 스레드가 동일한 프로세스에서 동시에 작동하는 경우 공유됩니다. 암호 , 데이터 섹션 및 파일과 같은 기타 운영 체제 리소스 열립니다 그리고 신호 . 기존 프로세스의 일종인 Heavyweight 프로세스는 하나의 스레드를 제어할 수 있습니다. 그러나 다중 스레드 제어에는 여러 작업을 동시에 열고 수행할 수 있는 기능이 있습니다. 스레드를 사용하면 시스템이 훨씬 더 효율적이게 되므로 스레드가 유용한 것입니다.

사이의 구별 하나의 그리고 멀티스레딩 C에서는 설명한다. 우선, 그것은 단일 스레드 프로세스 . 그 결과, 해당 블록을 포함한 전체 블록이 코드, 데이터, 등 - 하나의 프로세스로 간주되며 해당 프로세스에는 하나의 스레드만 있습니다. 이는 이 기술이 한 번에 하나의 작업만 완료한다는 것을 의미합니다. 그러나 거기에는 멀티스레딩 프로세스 이에 반대하는 것입니다. 등의 활동이 있습니다. 코드, 스택, 데이터 , 그리고 파일 마찬가지로 여러 스레드에 의해 수행되고 있으며 각 스레드에는 자체 스택과 레지스터가 있습니다. 이 상황에서는 수많은 작업을 한 번에 완료할 수 있다는 점을 감안할 때 이 프로세스를 멀티스레딩 프로세스 .

스레드는 두 가지 종류가 있습니다.

사용자 수준의 스레드:

이름에서 알 수 있듯이 사용자 수준에 있습니다. 커널에는 해당 데이터에 대한 액세스 권한이 부여되지 않습니다.

커널 수준의 스레드

스레드의 종류는 스레드와 시스템의 운영 체제 및 커널과의 관계를 나타냅니다.

프로세스- 프로그램을 수행하기 위해 취하는 일련의 단계를 다음과 같이 지칭할 수 있습니다. 프로세스 . 프로그램은 실행과 동시에 즉시 실행되지 않습니다. 이는 조직적인 방식으로 순차적으로 수행되어 결국 프로세스가 실행되는 몇 가지 기본 단계로 분류됩니다.

더 작은 단계로 나누어진 프로세스를 '복제 또는 하위 프로세스', 원래 프로세스를 '상위' 프로세스 . 메모리에서 각 프로세스는 다른 프로세스와 공유되지 않는 일정량의 공간을 사용합니다.

프로시저는 실행되기 전에 몇 가지 단계를 거칩니다.

새로운-

이런 상황에서 새로운 프로세스는 생성된 .

준비가 된-

프로세스가 준비되어 프로세서 할당을 기다리는 경우 이 상태입니다.

달리기-

프로세스가 활성화되면 상태가 됩니다.

정렬 목록 자바

대기 중-

프로세스가 이 상태에 있으면 뭔가가 발생합니다. 대기 중 일어날.

종료됨-

시술을 진행하고 있는 상태입니다.

C가 멀티스레드인 이유는 무엇입니까?

멀티스레딩 C 아이디어에서는 병렬성을 통해 활용하여 애플리케이션의 기능 . 브라우저 창에 여러 개의 탭이 열려 있는 경우를 생각해 보세요. 그런 다음 각 탭은 동시에 작동하며 . 우리가 사용한다고 가정하면 마이크로 소프트 엑셀 , 하나의 스레드가 관리합니다 텍스트 서식 , 그리고 하나의 스레드는 입력 처리 . 따라서 C의 멀티스레딩 기능을 사용하면 여러 작업을 동시에 수행하는 것이 간단해집니다. 스레드 생성이 훨씬 더 빨라졌습니다. 스레드 간 컨텍스트 전송이 더 빠르게 이루어집니다. 또한 스레드 간의 통신이 더 빠르게 이루어지고 스레드 종료가 간단해집니다.

멀티스레딩을 위한 C 프로그램을 작성하는 방법은 무엇입니까?

C 언어에는 멀티스레딩 응용 프로그램이 내장되어 있지 않지만 운영체제에 따라 가능합니다. 그만큼 thread.h 표준 라이브러리 멀티스레딩 아이디어를 구현하는 데 사용됩니다. . 그러나 현재 이를 수행할 수 있는 컴파일러는 없습니다. 우리는 다음과 같은 플랫폼별 구현을 사용해야 합니다. 'POSIX' 헤더 파일을 사용하여 스레드 라이브러리 pthread.h , C에서 멀티스레딩을 사용하려는 경우 'P스레드' 이것의 또 다른 이름입니다. ㅏ POSIX 스레드는 다음과 같은 방법으로 생성할 수 있습니다.

 #include pthread_create (thread, attr, start_routine, arg) 

이 경우, Pthread_create 스레드를 실행 가능하게 만들기 위해 새 스레드를 만듭니다. 이를 통해 코드에서 원하는 만큼 C에서 멀티스레딩을 구현할 수 있습니다. 이전의 매개변수와 해당 설명이 여기에 나열됩니다.

로마 숫자 1부터 100까지

실:

이것은 단수 식별 하위 프로세스 반환 .

속성:

스레드 속성을 설정하려면 다음을 사용합니다. 불투명 속성 .

시작_루틴:

언제 시작_루틴 생성되면 스레드가 루틴을 실행합니다.

인수:

매개변수는 시작_루틴 받습니다. 없는 인수가 제공되지 않으면 사용됩니다.

특정 C 멀티스레딩 예제

다음은 C의 멀티스레딩 문제에 대한 몇 가지 예입니다.

1. 독자-작가 문제

프로세스 동기화와 관련된 일반적인 운영 체제 문제는 리더/라이터 문제 . 다음과 같은 데이터베이스가 있다고 가정합니다. 독자 그리고 작가 , 두 가지 다른 사용자 카테고리에 액세스할 수 있습니다. 독자 할 수 있는 유일한 사람이야 읽다 데이터베이스는 반면 작가 데이터베이스를 읽고 업데이트할 수 있는 유일한 사람입니다. 사용하자 IRCTC 간단한 예로. 특정 상태를 확인하고 싶다면 열차 번호 , 해당 열차 정보를 보려면 시스템에 열차 번호를 입력하기만 하면 됩니다. 여기에는 웹사이트에 있는 정보만 표시됩니다. 읽기 연산자는 이것이다. 하지만 티켓을 예약하려면 이름, 나이 등과 같은 세부 정보를 티켓 예약 양식에 작성해야 합니다. 따라서 여기서는 쓰기 작업을 수행하겠습니다. 일부 조정이 있을 예정입니다. IRCTC 데이터베이스 .

문제는 여러 사람이 동시에 액세스를 시도하고 있다는 것입니다. IRCTC 데이터베이스 . 그들은 작가 또는 리더 . 독자가 이미 데이터베이스를 활용하고 있고 작성자가 동시에 액세스하여 동일한 데이터에 대해 작업하는 경우 문제가 발생합니다. 작성자가 데이터베이스를 사용하고, 독자가 데이터베이스와 동일한 정보에 액세스하는 경우 또 다른 문제가 발생합니다. 셋째, 한 작성자가 데이터베이스를 업데이트하는 동안 다른 작성자가 동일한 데이터베이스의 데이터를 업데이트하려고 할 때 어려움이 있습니다. 네 번째 시나리오는 두 명의 독자가 동일한 자료를 검색하려고 시도할 때 발생합니다. 이러한 모든 문제는 판독기와 기록기가 동일한 데이터베이스 데이터를 사용하는 경우 발생합니다.

이 문제를 해결하기 위해 사용되는 방법이 세마포어(Semaphore)입니다. 이 문제를 사용하는 방법에 대한 그림을 살펴보겠습니다.

리더 프로세스:

 #include #include #include int rc = 0; // Reader count int data = 0; // Shared data pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_twrt = PTHREAD_COND_INITIALIZER; void* reader(void* arg) { int reader_id = *(int*)arg; pthread_mutex_lock(&mutex); rc++; if (rc == 1) pthread_cond_wait(&wrt, &mutex); pthread_mutex_unlock(&mutex); // Reading the shared data printf('Reader %d reads data: %d
&apos;, reader_id, data); pthread_mutex_lock(&amp;mutex); rc--; if (rc == 0) pthread_cond_signal(&amp;wrt); pthread_mutex_unlock(&amp;mutex); return NULL; } int main() { pthread_treaders[5]; // Assuming 5 reader threads int reader_ids[5]; for (int i = 0; i<5; i++) { reader_ids[i]="i" + 1; pthread_create(&readers[i], null, reader, &reader_ids[i]); } joining reader threads for (int i="0;" i< 5; pthread_join(readers[i], null); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Reader 1 reads data: 0 Reader 2 reads data: 0 Reader 3 reads data: 0 Reader 4 reads data: 0 Reader 5 reads data: 0 </pre> <p> <strong>Explanation:</strong> </p> <p>In this code, we have the shared variable data and the <strong> <em>reader count rc</em> </strong> . The <strong> <em>wrt condition</em> </strong> variable is used to limit access for the <strong> <em>writer process</em> </strong> , and the <strong> <em>mutex</em> </strong> is used to guarantee mutual exclusion for accessing the shared data.</p> <p>The reader process is represented by the <strong> <em>reader() function</em> </strong> . The <strong> <em>reader count (rc)</em> </strong> is increased before attaining the <strong> <em>mutex lock</em> </strong> . It uses <strong> <em>pthread_cond_wait()</em> </strong> to wait on the <strong> <em>wrt condition</em> </strong> variable if it is the <strong> <em>first reader (rc == 1)</em> </strong> . As a result, writers will be prevented from writing until all readers have completed.</p> <p>The reader process checks if it was the <strong> <em>last reader (rc == 0)</em> </strong> and lowers the reader <strong> <em>count (rc--)</em> </strong> after reading the shared data. If it was, <strong> <em>pthread_cond_signal()</em> </strong> signals the <strong> <em>wrt condition</em> </strong> variable to let waiting writer processes continue.</p> <p>Using the <strong> <em>pthread_create()</em> </strong> and <strong> <em>pthread_join() functions</em> </strong> , we <strong> <em>new</em> </strong> and <strong> <em>join</em> </strong> multiple reader threads in the <strong> <em>main() function</em> </strong> . An individual ID is assigned to each reader thread for identifying purposes.</p> <h3>Writer process:</h3> <pre> wait(wrt); . . WRITE INTO THE OBJECT . signal(wrt); </pre> <p>In the above example, same as the <strong> <em>reader process</em> </strong> , an operation known as the wait operation is carried out on <strong> <em>&apos;wrt&apos;</em> </strong> when a user wishes to access the data or object. After that, the new user won&apos;t be able to access the object. And once the user has finished writing, another signal operation is performed on <strong> <em>wrt</em> </strong> .</p> <h3>2. lock and unlock problem:</h3> <p>The idea of a <strong> <em>mutex</em> </strong> is utilized in multithreading in C to guarantee that there won&apos;t be a <strong> <em>race condition</em> </strong> between the <strong> <em>threads</em> </strong> . When multiple threads begin processing the same data at once, this circumstance is known as <strong> <em>racing</em> </strong> . However, if these circumstances exist, we must. We use the <strong> <em>mutex&apos;s lock()</em> </strong> and <strong> <em>unlock() functions</em> </strong> to secure a particular section of code for a specific thread. Such that, another thread cannot begin performing the same operation. The <strong> <em>&apos;critical section/region&apos;</em> </strong> is the name given to this protected code area. Before using the shared resources, we set up a lot in a certain area, and once we&apos;ve finished using them, we unlock them once more.</p> <p>Let&apos;s examine the operation of the mutex for locking and unlocking in multithreading in C:</p> <p> <strong>Example:</strong> </p> <pre> #include #include #include pthread_mutex_tmy_mutex = PTHREAD_MUTEX_INITIALIZER; int shared_data = 0; void *thread_function(void *arg) { pthread_mutex_lock(&amp;my_mutex); shared_data++; // Modify the shared data printf(&apos;Thread %ld: Shared data modified. New value: %d
&apos;, (long)arg, shared_data); pthread_mutex_unlock(&amp;my_mutex); return NULL; } int main() { pthread_tthreads[5]; // Assuming 5 threads for (int i = 0; i<5; i++) { if (pthread_create(&threads[i], null, thread_function, (void *)(long)(i + 1)) !="0)" fprintf(stderr, 'error creating thread %d
', i 1); return 1; } for (int i< 5; (pthread_join(threads[i], null) joining 0; < pre> <p> <strong>Output:</strong> </p> <pre> Thread 1: Shared data modified. New value: 1 Thread 2: Shared data modified. New value: 2 Thread 3: Shared data modified. New value: 3 Thread 4: Shared data modified. New value: 4 Thread 5: Shared data modified. New value: 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this above example, we explain how we <strong> <em>lock</em> </strong> and <strong> <em>unlock</em> </strong> a certain region of code that shields us from the racing situation. <strong> <em>&apos;pthread_mutex_t&apos;</em> </strong> is used as an <strong> <em>initializer</em> </strong> in the example above. <strong> <em>&apos;pthread_mutex_lock&apos;</em> </strong> is then <strong> <em>written</em> </strong> before the beginning of the code that we want to lock. The coding that we wish to lock is finished after that. After that, the locking of the code is terminated using <strong> <em>&apos;pthread_mutex_unlock&apos;</em> </strong> ; going forward, no code will be in lock mode.</p> <h2>The Dining Philosopher Problem:</h2> <p>One of the classic issues with synchronization is the <strong> <em>dining philosopher issue</em> </strong> . Simple resource allocation for several processes is required but shouldn&apos;t result in a <strong> <em>stalemate</em> </strong> or <strong> <em>hunger</em> </strong> . The <strong> <em>dining philosopher problem</em> </strong> can be viewed as a straightforward representation of a number of processes, each of which is demanding resources. Since each of these processes requires a resource allocation, it is necessary to distribute those resources across all of the processes so that no one process ever gets stuck or stops working.</p> <p>Assume there are five philosophers seated at a <strong> <em>circle-shaped table</em> </strong> . They eat at one point and ponder about something at another. Around the round table, the philosophers are evenly spaced out on the chairs. Additionally, there is a bowl of rice and five chopsticks for each philosopher in the middle of the table. When the philosopher feels she cannot interact with her colleagues who are seated nearby.</p> <p>A philosopher occasionally takes up two chopsticks when she becomes hungry. She chooses two chopsticks from her neighbors-one on her <strong> <em>left</em> </strong> and one on her <strong> <em>right</em> </strong> -that are within easy reach. But the philosopher should never pick up more than one chopstick at once. She will obviously be unable to pick up the chopstick that the neighbor is using.</p> <p> <strong>Example:</strong> </p> <p>Let&apos;s use an example to demonstrate how this is implemented in C.</p> <pre> #include #include #include #include #include pthread_tphilosopher[5]; pthread_mutex_tchopstick[5]; void *func(void *arg) { int n = *(int *)arg; printf(&apos;
Philosopher %d is thinking.&apos;, n); pthread_mutex_lock(&amp;chopstick[n]); pthread_mutex_lock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d is eating.&apos;, n); sleep(3); pthread_mutex_unlock(&amp;chopstick[n]); pthread_mutex_unlock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d Finished eating &apos;, n); return NULL; } int main() { int i, k; void *message; for (i = 0; i<5; i++) { k="pthread_mutex_init(&amp;chopstick[i]," null); if (k !="0)" printf('failed to initialize the mutex
'); exit(1); } for (i="0;" i< 5; null, func, (void *)&i); printf('error in thread creation.
'); &message); join thread.
'); printf('mutex destroyed.
'); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Philosopher 0 is thinking. Philosopher 1 is thinking. Philosopher 2 is thinking. Philosopher 3 is thinking. Philosopher 4 is thinking. Philosopher 0 is eating. Philosopher 1 is eating. Philosopher 2 is eating. Philosopher 3 is eating. Philosopher 4 is eating. Philosopher 0 Finished eating Philosopher 1 Finished eating Philosopher 2 Finished eating Philosopher 3 Finished eating Philosopher 4 Finished eating </pre> <p> <strong>Explanation:</strong> </p> <p> <strong> <em>Chopsticks</em> </strong> can be represented by a semaphore. Since there are <strong> <em>chopsticks</em> </strong> on the table and no philosopher has chosen one, all of the chopsticks&apos; components are first initialized to <strong> <em>1</em> </strong> . Now that <strong> <em>chopstick[i]</em> </strong> has been chosen as the first <strong> <em>chopstick. chopstick[i]</em> </strong> and <strong> <em>chopstick[(i+1)%5]</em> </strong> are subject to the first wait operation. These <strong> <em>chopsticks&apos; wait operation</em> </strong> indicates that the philosopher has picked them up. The eating process begins once the philosopher selects his <strong> <em>chopstick</em> </strong> . The signal operation is now carried out on the <strong> <em>chopsticks [i]</em> </strong> and <strong> <em>[(i+1)%5]</em> </strong> once the philosopher has finished eating. The philosopher then turns back to sleep.</p> <p>To determine whether the <strong> <em>subthread</em> </strong> has joined the main thread or not, we used the <strong> <em>pthread_join function</em> </strong> . Similarly, we have checked whether the <strong> <em>mutex</em> </strong> lock has been initialized using the <strong> <em>pthread_mutex_init</em> </strong> method.</p> <p>To initialize and verify whether the new thread was created or not, we utilized the <strong> <em>pthread_create function</em> </strong> . Similar to this, we destroyed the <strong> <em>mutex lock</em> </strong> using the <strong> <em>pthread_mutex_destroy</em> </strong> function.</p> <h2>The Producer-Consumer Problem:</h2> <p>A common issue with multithreading process synchronization is the <strong> <em>producer-consumer problem</em> </strong> . Two processes are present in it: the first is the <strong> <em>producer&apos;s process</em> </strong> , and the second is the <strong> <em>consumer&apos;s process</em> </strong> . Furthermore, it is assumed that both operations are occurring concurrently in parallel. Additionally, they are a cooperative process, which implies that they are sharing something with one another. It is important that when the buffer is <strong> <em>full</em> </strong> , the producer cannot add data. When the buffer is empty, the consumer cannot extract data from the buffer because the common buffer size between the producer and the consumer is <strong> <em>fixed</em> </strong> . The issue is stated in this way. Hence, to implement the Producer-Consumer problem and solve it, we shall employ the idea of parallel programming.</p> <p> <strong>Example:</strong> </p> <pre> #include #include int mutex = 1, full = 0, empty = 3, x = 0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf(&apos;
1.producer
2.consumer
3.for exit&apos;); while (1) { printf(&apos;
 Please enter your choice:&apos;); scanf(&apos;%d&apos;, &amp;n); switch (n) { case 1: if ((mutex == 1) &amp;&amp; (empty != 0)) producer(); else printf(&apos;Oops!! the buffer is full!!&apos;); break; case 2: if ((mutex == 1) &amp;&amp; (full != 0)) consumer(); else printf(&apos;Oops!! the buffer is empty!!&apos;); break; case 3: exit(0); break; } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return (++s); } void producer() { mutex = wait(mutex); full = signal(full); empty = wait(empty); x++; printf(&apos;
Item produced by the Producer %d&apos;, x); mutex = signal(mutex); } void consumer() { mutex = wait(mutex); full = wait(full); empty = signal(empty); printf(&apos;
Item consumed by the Consumer %d&apos;, x); x--; mutex = signal(mutex); } </pre> <p> <strong>Output:</strong> </p> <pre> 1. producer 2. consumer 3. for exit Please enter your choice: </pre> <p> <strong>Explanation:</strong> </p> <p>We perform two tasks. The functions <strong> <em>consumer()</em> </strong> and <strong> <em>producer()</em> </strong> indicate the status and operation of the <strong> <em>consumer</em> </strong> and <strong> <em>producer</em> </strong> . The <strong> <em>producer() method</em> </strong> will create the <strong> <em>mutex lock</em> </strong> and determine whether the buffer is <strong> <em>full</em> </strong> when it is called. When the buffer is full, nothing will be produced. If not, it will <strong> <em>create</em> </strong> , and then, after the <strong> <em>production</em> </strong> , it will put itself to sleep to unlock the <strong> <em>mutex lock</em> </strong> . Like the <strong> <em>producer</em> </strong> , the consumer first creates the <strong> <em>mutex lock</em> </strong> , checks the <strong> <em>buffer</em> </strong> , consumes the <strong> <em>product</em> </strong> , and then releases the lock before going back to sleep.</p> <p>A <strong> <em>counter (x)</em> </strong> will be used during manufacturing and will keep growing until the manufacturer produces the item. However, the consumer will make fewer of the same manufactured <strong> <em>item (x)</em> </strong> .</p> <h2>Conclusion:</h2> <p>The idea of using <strong> <em>two</em> </strong> or <strong> <em>more threads</em> </strong> to execute a program is known as <strong> <em>multithreading</em> </strong> in the C programming language. <strong> <em>Multithreading</em> </strong> allows for the simultaneous execution of several tasks. The simplest executable component of a program is a <strong> <em>thread</em> </strong> . The process is the idea that a task can be completed by breaking it up into several smaller <strong> <em>sub-processes</em> </strong> .</p> <p>The header file <strong> <em>pthread.h</em> </strong> is required in order to implement multithreading in C since it cannot be done directly.</p> <hr></5;></pre></5;></pre></5;>

설명:

이 코드에는 공유 변수 데이터와 독자 수 rc . 그만큼 최악의 조건 변수는 액세스를 제한하는 데 사용됩니다. 작가 과정 , 그리고 뮤텍스 공유 데이터에 대한 액세스에 대한 상호 배제를 보장하는 데 사용됩니다.

리더 프로세스는 다음과 같이 표현됩니다. 리더() 함수 . 그만큼 독자 수(rc) 도달하기 전에 증가합니다. 뮤텍스 잠금 . 그것은 사용한다 pthread_cond_wait() 기다리다 최악의 조건 변수인 경우 첫 번째 리더(rc == 1) . 결과적으로 모든 독자가 완료할 때까지 작성자는 글을 쓸 수 없습니다.

리더 프로세스는 그것이 마지막 판독기(rc == 0) 그리고 독자를 낮추다 개수(rc--) 공유 데이터를 읽은 후. 그랬다면, pthread_cond_signal() 신호를 보낸다 최악의 조건 대기 중인 작성기 프로세스를 계속할 수 있도록 하는 변수입니다.

사용하여 pthread_create() 그리고 pthread_join() 함수 , 우리 새로운 그리고 가입하다 다중 리더 스레드 주요 기능 . 식별 목적으로 각 리더 스레드에 개별 ID가 할당됩니다.

작가 과정:

 wait(wrt); . . WRITE INTO THE OBJECT . signal(wrt); 

위의 예에서는 리더 프로세스 , 대기 작업으로 알려진 작업이 수행됩니다. '워트' 사용자가 데이터나 객체에 접근하려고 할 때. 그 후에는 새 사용자가 개체에 액세스할 수 없습니다. 그리고 사용자가 쓰기를 마치면 다른 신호 작업이 수행됩니다. wrt .

2. 잠금 및 잠금 해제 문제:

아이디어 뮤텍스 C의 멀티스레딩에 사용되어 오류가 발생하지 않도록 보장합니다. 경쟁 조건 사이에 스레드 . 여러 스레드가 동시에 동일한 데이터 처리를 시작하는 경우를 이러한 상황이라고 합니다. 경마 . 그러나 이러한 상황이 존재한다면 우리는 그렇게 해야 합니다. 우리는 뮤텍스의 lock() 그리고 잠금해제() 함수 특정 스레드에 대한 특정 코드 섹션을 보호합니다. 따라서 다른 스레드는 동일한 작업 수행을 시작할 수 없습니다. 그만큼 '중요 섹션/지역' 이 보호 코드 영역에 지정된 이름입니다. 공유자원을 사용하기 전에 특정 지역에 많은 것을 설정하고, 사용이 끝나면 다시 한 번 잠금을 해제합니다.

C의 멀티스레딩에서 잠금 및 잠금 해제를 위한 뮤텍스의 작동을 살펴보겠습니다.

예:

 #include #include #include pthread_mutex_tmy_mutex = PTHREAD_MUTEX_INITIALIZER; int shared_data = 0; void *thread_function(void *arg) { pthread_mutex_lock(&amp;my_mutex); shared_data++; // Modify the shared data printf(&apos;Thread %ld: Shared data modified. New value: %d
&apos;, (long)arg, shared_data); pthread_mutex_unlock(&amp;my_mutex); return NULL; } int main() { pthread_tthreads[5]; // Assuming 5 threads for (int i = 0; i<5; i++) { if (pthread_create(&threads[i], null, thread_function, (void *)(long)(i + 1)) !="0)" fprintf(stderr, \'error creating thread %d
\', i 1); return 1; } for (int i< 5; (pthread_join(threads[i], null) joining 0; < pre> <p> <strong>Output:</strong> </p> <pre> Thread 1: Shared data modified. New value: 1 Thread 2: Shared data modified. New value: 2 Thread 3: Shared data modified. New value: 3 Thread 4: Shared data modified. New value: 4 Thread 5: Shared data modified. New value: 5 </pre> <p> <strong>Explanation:</strong> </p> <p>In this above example, we explain how we <strong> <em>lock</em> </strong> and <strong> <em>unlock</em> </strong> a certain region of code that shields us from the racing situation. <strong> <em>&apos;pthread_mutex_t&apos;</em> </strong> is used as an <strong> <em>initializer</em> </strong> in the example above. <strong> <em>&apos;pthread_mutex_lock&apos;</em> </strong> is then <strong> <em>written</em> </strong> before the beginning of the code that we want to lock. The coding that we wish to lock is finished after that. After that, the locking of the code is terminated using <strong> <em>&apos;pthread_mutex_unlock&apos;</em> </strong> ; going forward, no code will be in lock mode.</p> <h2>The Dining Philosopher Problem:</h2> <p>One of the classic issues with synchronization is the <strong> <em>dining philosopher issue</em> </strong> . Simple resource allocation for several processes is required but shouldn&apos;t result in a <strong> <em>stalemate</em> </strong> or <strong> <em>hunger</em> </strong> . The <strong> <em>dining philosopher problem</em> </strong> can be viewed as a straightforward representation of a number of processes, each of which is demanding resources. Since each of these processes requires a resource allocation, it is necessary to distribute those resources across all of the processes so that no one process ever gets stuck or stops working.</p> <p>Assume there are five philosophers seated at a <strong> <em>circle-shaped table</em> </strong> . They eat at one point and ponder about something at another. Around the round table, the philosophers are evenly spaced out on the chairs. Additionally, there is a bowl of rice and five chopsticks for each philosopher in the middle of the table. When the philosopher feels she cannot interact with her colleagues who are seated nearby.</p> <p>A philosopher occasionally takes up two chopsticks when she becomes hungry. She chooses two chopsticks from her neighbors-one on her <strong> <em>left</em> </strong> and one on her <strong> <em>right</em> </strong> -that are within easy reach. But the philosopher should never pick up more than one chopstick at once. She will obviously be unable to pick up the chopstick that the neighbor is using.</p> <p> <strong>Example:</strong> </p> <p>Let&apos;s use an example to demonstrate how this is implemented in C.</p> <pre> #include #include #include #include #include pthread_tphilosopher[5]; pthread_mutex_tchopstick[5]; void *func(void *arg) { int n = *(int *)arg; printf(&apos;
Philosopher %d is thinking.&apos;, n); pthread_mutex_lock(&amp;chopstick[n]); pthread_mutex_lock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d is eating.&apos;, n); sleep(3); pthread_mutex_unlock(&amp;chopstick[n]); pthread_mutex_unlock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d Finished eating &apos;, n); return NULL; } int main() { int i, k; void *message; for (i = 0; i<5; i++) { k="pthread_mutex_init(&amp;chopstick[i]," null); if (k !="0)" printf(\'failed to initialize the mutex
\'); exit(1); } for (i="0;" i< 5; null, func, (void *)&i); printf(\'error in thread creation.
\'); &message); join thread.
\'); printf(\'mutex destroyed.
\'); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Philosopher 0 is thinking. Philosopher 1 is thinking. Philosopher 2 is thinking. Philosopher 3 is thinking. Philosopher 4 is thinking. Philosopher 0 is eating. Philosopher 1 is eating. Philosopher 2 is eating. Philosopher 3 is eating. Philosopher 4 is eating. Philosopher 0 Finished eating Philosopher 1 Finished eating Philosopher 2 Finished eating Philosopher 3 Finished eating Philosopher 4 Finished eating </pre> <p> <strong>Explanation:</strong> </p> <p> <strong> <em>Chopsticks</em> </strong> can be represented by a semaphore. Since there are <strong> <em>chopsticks</em> </strong> on the table and no philosopher has chosen one, all of the chopsticks&apos; components are first initialized to <strong> <em>1</em> </strong> . Now that <strong> <em>chopstick[i]</em> </strong> has been chosen as the first <strong> <em>chopstick. chopstick[i]</em> </strong> and <strong> <em>chopstick[(i+1)%5]</em> </strong> are subject to the first wait operation. These <strong> <em>chopsticks&apos; wait operation</em> </strong> indicates that the philosopher has picked them up. The eating process begins once the philosopher selects his <strong> <em>chopstick</em> </strong> . The signal operation is now carried out on the <strong> <em>chopsticks [i]</em> </strong> and <strong> <em>[(i+1)%5]</em> </strong> once the philosopher has finished eating. The philosopher then turns back to sleep.</p> <p>To determine whether the <strong> <em>subthread</em> </strong> has joined the main thread or not, we used the <strong> <em>pthread_join function</em> </strong> . Similarly, we have checked whether the <strong> <em>mutex</em> </strong> lock has been initialized using the <strong> <em>pthread_mutex_init</em> </strong> method.</p> <p>To initialize and verify whether the new thread was created or not, we utilized the <strong> <em>pthread_create function</em> </strong> . Similar to this, we destroyed the <strong> <em>mutex lock</em> </strong> using the <strong> <em>pthread_mutex_destroy</em> </strong> function.</p> <h2>The Producer-Consumer Problem:</h2> <p>A common issue with multithreading process synchronization is the <strong> <em>producer-consumer problem</em> </strong> . Two processes are present in it: the first is the <strong> <em>producer&apos;s process</em> </strong> , and the second is the <strong> <em>consumer&apos;s process</em> </strong> . Furthermore, it is assumed that both operations are occurring concurrently in parallel. Additionally, they are a cooperative process, which implies that they are sharing something with one another. It is important that when the buffer is <strong> <em>full</em> </strong> , the producer cannot add data. When the buffer is empty, the consumer cannot extract data from the buffer because the common buffer size between the producer and the consumer is <strong> <em>fixed</em> </strong> . The issue is stated in this way. Hence, to implement the Producer-Consumer problem and solve it, we shall employ the idea of parallel programming.</p> <p> <strong>Example:</strong> </p> <pre> #include #include int mutex = 1, full = 0, empty = 3, x = 0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf(&apos;
1.producer
2.consumer
3.for exit&apos;); while (1) { printf(&apos;
 Please enter your choice:&apos;); scanf(&apos;%d&apos;, &amp;n); switch (n) { case 1: if ((mutex == 1) &amp;&amp; (empty != 0)) producer(); else printf(&apos;Oops!! the buffer is full!!&apos;); break; case 2: if ((mutex == 1) &amp;&amp; (full != 0)) consumer(); else printf(&apos;Oops!! the buffer is empty!!&apos;); break; case 3: exit(0); break; } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return (++s); } void producer() { mutex = wait(mutex); full = signal(full); empty = wait(empty); x++; printf(&apos;
Item produced by the Producer %d&apos;, x); mutex = signal(mutex); } void consumer() { mutex = wait(mutex); full = wait(full); empty = signal(empty); printf(&apos;
Item consumed by the Consumer %d&apos;, x); x--; mutex = signal(mutex); } </pre> <p> <strong>Output:</strong> </p> <pre> 1. producer 2. consumer 3. for exit Please enter your choice: </pre> <p> <strong>Explanation:</strong> </p> <p>We perform two tasks. The functions <strong> <em>consumer()</em> </strong> and <strong> <em>producer()</em> </strong> indicate the status and operation of the <strong> <em>consumer</em> </strong> and <strong> <em>producer</em> </strong> . The <strong> <em>producer() method</em> </strong> will create the <strong> <em>mutex lock</em> </strong> and determine whether the buffer is <strong> <em>full</em> </strong> when it is called. When the buffer is full, nothing will be produced. If not, it will <strong> <em>create</em> </strong> , and then, after the <strong> <em>production</em> </strong> , it will put itself to sleep to unlock the <strong> <em>mutex lock</em> </strong> . Like the <strong> <em>producer</em> </strong> , the consumer first creates the <strong> <em>mutex lock</em> </strong> , checks the <strong> <em>buffer</em> </strong> , consumes the <strong> <em>product</em> </strong> , and then releases the lock before going back to sleep.</p> <p>A <strong> <em>counter (x)</em> </strong> will be used during manufacturing and will keep growing until the manufacturer produces the item. However, the consumer will make fewer of the same manufactured <strong> <em>item (x)</em> </strong> .</p> <h2>Conclusion:</h2> <p>The idea of using <strong> <em>two</em> </strong> or <strong> <em>more threads</em> </strong> to execute a program is known as <strong> <em>multithreading</em> </strong> in the C programming language. <strong> <em>Multithreading</em> </strong> allows for the simultaneous execution of several tasks. The simplest executable component of a program is a <strong> <em>thread</em> </strong> . The process is the idea that a task can be completed by breaking it up into several smaller <strong> <em>sub-processes</em> </strong> .</p> <p>The header file <strong> <em>pthread.h</em> </strong> is required in order to implement multithreading in C since it cannot be done directly.</p> <hr></5;></pre></5;>

설명:

Java에서 문자열을 정수로 변환하는 방법

위의 예에서는 잠그다 그리고 터놓다 경주 상황으로부터 우리를 보호하는 특정 코드 영역. 'pthread_mutex_t' 로 사용됩니다 초기화 위의 예에서. 'pthread_mutex_lock' 그렇다면 잠그려는 코드가 시작되기 전에. 그 후에 잠그려는 코딩이 완료됩니다. 그 후 다음을 사용하여 코드 잠금이 종료됩니다. 'pthread_mutex_unlock' ; 앞으로는 잠금 모드에 있는 코드가 없습니다.

식사 철학자의 문제:

동기화와 관련된 고전적인 문제 중 하나는 식사 철학자 문제 . 여러 프로세스에 대한 간단한 리소스 할당이 필요하지만 결과적으로 수가 막히게 하다 또는 굶주림 . 그만큼 식사하는 철학자 문제 각 프로세스에는 리소스가 필요하므로 여러 프로세스를 간단하게 표현한 것으로 볼 수 있습니다. 이러한 각 프로세스에는 리소스 할당이 필요하므로 프로세스가 중단되거나 작동이 중단되지 않도록 모든 프로세스에 해당 리소스를 배포해야 합니다.

다섯 명의 철학자가 한 자리에 앉아 있다고 가정하자. 원형 테이블 . 그들은 한 시점에서 먹고 다른 시점에서 무언가에 대해 숙고합니다. 원형 테이블을 중심으로 의자 위에는 철학자들이 고르게 간격을 두고 배치되어 있습니다. 그리고 테이블 중앙에는 철학자 한 명당 밥 한 그릇과 젓가락 다섯 개가 놓여 있습니다. 철학자는 근처에 앉아 있는 동료들과 교류할 수 없다고 느낄 때.

네트워크와 인터넷

철학자는 가끔 배가 고프면 젓가락 두 개를 집습니다. 그녀는 이웃에게서 젓가락 두 개를 선택합니다. 하나는 자신의 젓가락입니다. 왼쪽 그리고 그녀한테 하나 오른쪽 -쉽게 접근할 수 있는 거리에 있습니다. 그러나 철학자는 한 번에 두 개 이상의 젓가락을 집어들어서는 안 됩니다. 분명히 그녀는 이웃이 사용하고 있는 젓가락을 집을 수 없을 것입니다.

예:

예제를 사용하여 이것이 C에서 어떻게 구현되는지 보여드리겠습니다.

 #include #include #include #include #include pthread_tphilosopher[5]; pthread_mutex_tchopstick[5]; void *func(void *arg) { int n = *(int *)arg; printf(&apos;
Philosopher %d is thinking.&apos;, n); pthread_mutex_lock(&amp;chopstick[n]); pthread_mutex_lock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d is eating.&apos;, n); sleep(3); pthread_mutex_unlock(&amp;chopstick[n]); pthread_mutex_unlock(&amp;chopstick[(n + 1) % 5]); printf(&apos;
Philosopher %d Finished eating &apos;, n); return NULL; } int main() { int i, k; void *message; for (i = 0; i<5; i++) { k="pthread_mutex_init(&amp;chopstick[i]," null); if (k !="0)" printf(\'failed to initialize the mutex
\'); exit(1); } for (i="0;" i< 5; null, func, (void *)&i); printf(\'error in thread creation.
\'); &message); join thread.
\'); printf(\'mutex destroyed.
\'); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Philosopher 0 is thinking. Philosopher 1 is thinking. Philosopher 2 is thinking. Philosopher 3 is thinking. Philosopher 4 is thinking. Philosopher 0 is eating. Philosopher 1 is eating. Philosopher 2 is eating. Philosopher 3 is eating. Philosopher 4 is eating. Philosopher 0 Finished eating Philosopher 1 Finished eating Philosopher 2 Finished eating Philosopher 3 Finished eating Philosopher 4 Finished eating </pre> <p> <strong>Explanation:</strong> </p> <p> <strong> <em>Chopsticks</em> </strong> can be represented by a semaphore. Since there are <strong> <em>chopsticks</em> </strong> on the table and no philosopher has chosen one, all of the chopsticks&apos; components are first initialized to <strong> <em>1</em> </strong> . Now that <strong> <em>chopstick[i]</em> </strong> has been chosen as the first <strong> <em>chopstick. chopstick[i]</em> </strong> and <strong> <em>chopstick[(i+1)%5]</em> </strong> are subject to the first wait operation. These <strong> <em>chopsticks&apos; wait operation</em> </strong> indicates that the philosopher has picked them up. The eating process begins once the philosopher selects his <strong> <em>chopstick</em> </strong> . The signal operation is now carried out on the <strong> <em>chopsticks [i]</em> </strong> and <strong> <em>[(i+1)%5]</em> </strong> once the philosopher has finished eating. The philosopher then turns back to sleep.</p> <p>To determine whether the <strong> <em>subthread</em> </strong> has joined the main thread or not, we used the <strong> <em>pthread_join function</em> </strong> . Similarly, we have checked whether the <strong> <em>mutex</em> </strong> lock has been initialized using the <strong> <em>pthread_mutex_init</em> </strong> method.</p> <p>To initialize and verify whether the new thread was created or not, we utilized the <strong> <em>pthread_create function</em> </strong> . Similar to this, we destroyed the <strong> <em>mutex lock</em> </strong> using the <strong> <em>pthread_mutex_destroy</em> </strong> function.</p> <h2>The Producer-Consumer Problem:</h2> <p>A common issue with multithreading process synchronization is the <strong> <em>producer-consumer problem</em> </strong> . Two processes are present in it: the first is the <strong> <em>producer&apos;s process</em> </strong> , and the second is the <strong> <em>consumer&apos;s process</em> </strong> . Furthermore, it is assumed that both operations are occurring concurrently in parallel. Additionally, they are a cooperative process, which implies that they are sharing something with one another. It is important that when the buffer is <strong> <em>full</em> </strong> , the producer cannot add data. When the buffer is empty, the consumer cannot extract data from the buffer because the common buffer size between the producer and the consumer is <strong> <em>fixed</em> </strong> . The issue is stated in this way. Hence, to implement the Producer-Consumer problem and solve it, we shall employ the idea of parallel programming.</p> <p> <strong>Example:</strong> </p> <pre> #include #include int mutex = 1, full = 0, empty = 3, x = 0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf(&apos;
1.producer
2.consumer
3.for exit&apos;); while (1) { printf(&apos;
 Please enter your choice:&apos;); scanf(&apos;%d&apos;, &amp;n); switch (n) { case 1: if ((mutex == 1) &amp;&amp; (empty != 0)) producer(); else printf(&apos;Oops!! the buffer is full!!&apos;); break; case 2: if ((mutex == 1) &amp;&amp; (full != 0)) consumer(); else printf(&apos;Oops!! the buffer is empty!!&apos;); break; case 3: exit(0); break; } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return (++s); } void producer() { mutex = wait(mutex); full = signal(full); empty = wait(empty); x++; printf(&apos;
Item produced by the Producer %d&apos;, x); mutex = signal(mutex); } void consumer() { mutex = wait(mutex); full = wait(full); empty = signal(empty); printf(&apos;
Item consumed by the Consumer %d&apos;, x); x--; mutex = signal(mutex); } </pre> <p> <strong>Output:</strong> </p> <pre> 1. producer 2. consumer 3. for exit Please enter your choice: </pre> <p> <strong>Explanation:</strong> </p> <p>We perform two tasks. The functions <strong> <em>consumer()</em> </strong> and <strong> <em>producer()</em> </strong> indicate the status and operation of the <strong> <em>consumer</em> </strong> and <strong> <em>producer</em> </strong> . The <strong> <em>producer() method</em> </strong> will create the <strong> <em>mutex lock</em> </strong> and determine whether the buffer is <strong> <em>full</em> </strong> when it is called. When the buffer is full, nothing will be produced. If not, it will <strong> <em>create</em> </strong> , and then, after the <strong> <em>production</em> </strong> , it will put itself to sleep to unlock the <strong> <em>mutex lock</em> </strong> . Like the <strong> <em>producer</em> </strong> , the consumer first creates the <strong> <em>mutex lock</em> </strong> , checks the <strong> <em>buffer</em> </strong> , consumes the <strong> <em>product</em> </strong> , and then releases the lock before going back to sleep.</p> <p>A <strong> <em>counter (x)</em> </strong> will be used during manufacturing and will keep growing until the manufacturer produces the item. However, the consumer will make fewer of the same manufactured <strong> <em>item (x)</em> </strong> .</p> <h2>Conclusion:</h2> <p>The idea of using <strong> <em>two</em> </strong> or <strong> <em>more threads</em> </strong> to execute a program is known as <strong> <em>multithreading</em> </strong> in the C programming language. <strong> <em>Multithreading</em> </strong> allows for the simultaneous execution of several tasks. The simplest executable component of a program is a <strong> <em>thread</em> </strong> . The process is the idea that a task can be completed by breaking it up into several smaller <strong> <em>sub-processes</em> </strong> .</p> <p>The header file <strong> <em>pthread.h</em> </strong> is required in order to implement multithreading in C since it cannot be done directly.</p> <hr></5;>

설명:

젓가락 세마포어로 표현될 수 있다. 있기 때문에 젓가락 탁자 위에서 철학자가 하나를 선택하지 않은 경우, 젓가락의 모든 구성 요소가 먼저 초기화됩니다. 1 . 이제 그 젓가락[i] 첫 번째로 선정되었습니다 젓가락. 젓가락[i] 그리고 젓가락[(i+1)%5] 첫 번째 대기 작업이 적용됩니다. 이것들 젓가락 대기 동작 철학자가 그것을 집어 들었다는 것을 나타냅니다. 철학자가 음식을 선택하면 식사 과정이 시작됩니다. 젓가락 . 이제 신호 작업이 다음에서 수행됩니다. 젓가락 [나] 그리고 [(i+1)%5] 철학자가 식사를 마치면. 철학자는 다시 잠에 빠진다.

여부를 결정하려면 하위 스레드 메인 스레드에 합류했는지 여부에 따라 우리는 pthread_join 함수 . 마찬가지로, 우리는 뮤텍스 잠금은 다음을 사용하여 초기화되었습니다. pthread_mutex_init 방법.

새 스레드가 생성되었는지 여부를 초기화하고 확인하기 위해 우리는 다음을 활용했습니다. pthread_create 함수 . 이와 유사하게 우리는 뮤텍스 잠금 사용하여 pthread_mutex_destroy 기능.

생산자-소비자 문제:

멀티스레딩 프로세스 동기화의 일반적인 문제는 생산자-소비자 문제 . 여기에는 두 가지 프로세스가 있습니다. 첫 번째는 생산자의 과정 , 그리고 두 번째는 소비자의 프로세스 . 또한 두 작업이 동시에 병렬로 발생한다고 가정합니다. 또한 이는 협력적인 프로세스로, 이는 서로 무언가를 공유하고 있음을 의미합니다. 버퍼가 있을 때 중요합니다. 가득한 , 생산자는 데이터를 추가할 수 없습니다. 버퍼가 비어 있으면 생산자와 소비자 사이의 공통 버퍼 크기가 다음과 같기 때문에 소비자는 버퍼에서 데이터를 추출할 수 없습니다. 결정된 . 문제는 이렇게 명시되어 있습니다. 따라서 생산자-소비자 문제를 구현하고 해결하기 위해 병렬 프로그래밍 아이디어를 적용하겠습니다.

예:

 #include #include int mutex = 1, full = 0, empty = 3, x = 0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf(&apos;
1.producer
2.consumer
3.for exit&apos;); while (1) { printf(&apos;
 Please enter your choice:&apos;); scanf(&apos;%d&apos;, &amp;n); switch (n) { case 1: if ((mutex == 1) &amp;&amp; (empty != 0)) producer(); else printf(&apos;Oops!! the buffer is full!!&apos;); break; case 2: if ((mutex == 1) &amp;&amp; (full != 0)) consumer(); else printf(&apos;Oops!! the buffer is empty!!&apos;); break; case 3: exit(0); break; } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return (++s); } void producer() { mutex = wait(mutex); full = signal(full); empty = wait(empty); x++; printf(&apos;
Item produced by the Producer %d&apos;, x); mutex = signal(mutex); } void consumer() { mutex = wait(mutex); full = wait(full); empty = signal(empty); printf(&apos;
Item consumed by the Consumer %d&apos;, x); x--; mutex = signal(mutex); } 

산출:

 1. producer 2. consumer 3. for exit Please enter your choice: 

설명:

우리는 두 가지 작업을 수행합니다. 기능 소비자() 그리고 생산자() 상태와 작동을 나타냅니다. 소비자 그리고 생산자 . 그만큼 생산자() 메서드 을 만들 것입니다 뮤텍스 잠금 버퍼가 다음과 같은지 여부를 확인합니다. 가득한 그것이 호출될 때. 버퍼가 가득 차면 아무것도 생성되지 않습니다. 그렇지 않다면 그럴 것이다. 만들다 , 그리고 나서 생산 , 잠금을 해제하기 위해 절전 모드로 전환됩니다. 뮤텍스 잠금 . 처럼 생산자 , 소비자가 먼저 뮤텍스 잠금 , 확인 완충기 , 소비한다 제품 를 누른 다음 다시 절전 모드로 전환하기 전에 잠금을 해제합니다.

카운터(x) 제조 과정에서 사용되며 제조업체가 품목을 생산할 때까지 계속 증가합니다. 그러나 소비자는 동일한 제품을 더 적게 만들 것입니다. 항목 (x) .

결론:

사용하는 아이디어 또는 더 많은 스레드 프로그램을 실행하는 것을 다음과 같이 알려져 있습니다. 멀티스레딩 C 프로그래밍 언어로. 멀티스레딩 여러 작업을 동시에 실행할 수 있습니다. 프로그램의 가장 간단한 실행 가능 구성요소는 . 프로세스는 작업을 여러 개의 작은 부분으로 나누어 완료할 수 있다는 아이디어입니다. 하위 프로세스 .

헤더 파일 pthread.h C에서 멀티스레딩을 구현하려면 직접 수행할 수 없기 때문에 필요합니다.