スレッド同期を使用して番号を順番に出力します
ここでは、さまざまなスレッドを使用して正しい順序で数字を印刷する方法を説明します。ここでは、n個のスレッドを作成し、それらを同期します。つまり、最初のスレッドは1を印刷し、次に2番目のスレッドは2を印刷します。 1つのスレッドが印刷しようとすると、リソースがロックされるため、その部分を使用できるスレッドはありません。
例
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t* cond = NULL;
int threads;
volatile int count = 0;
void* sync_thread(void* num) { //this function is used to synchronize the threads
int thread_number = *(int*)num;
while (1) {
pthread_mutex_lock(&mutex); //lock the section
if (thread_number != count) { //if the thread number is not same as count, put all thread
except one into waiting state
pthread_cond_wait(&cond[thread_number], &mutex);
}
printf("%d ", thread_number + 1); //print the thread number
count = (count+1)%(threads);
// notify the next thread
pthread_cond_signal(&cond[count]);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t* thread_id;
volatile int i;
int* thread_arr;
printf("\nEnter number of threads: ");
scanf("%d", &threads);
// allocate memory to cond (conditional variable) thread id's and array of size threads
cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads);
thread_id = (pthread_t*)malloc(sizeof(pthread_t) * threads);
thread_arr = (int*)malloc(sizeof(int) * threads);
for (i = 0; i < threads; i++) { //create threads
thread_arr[i] = i;
pthread_create(&thread_id[i], NULL, sync_thread, (void*)&thread_arr[i]);
}
// waiting for thread
for (i = 0; i < threads; i++) {
pthread_join(thread_id[i], NULL);
}
return 0;
} 出力
$ g++ test.cpp -lpthread $ ./a.out Enter number of threads: 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 ... ... ...
-
Cで数値列を賢く印刷するプログラム
プログラムの説明 以下に示すように、自然数の列を賢く印刷します 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15 アルゴリズム i stands for rows and j stands for columns. 5 stands for making pattern for 5 Rows and Columns Loop for each Row (i) K is initialized to i Loop for each Column (j) Do the Pattern for the current Column (j) Display the Value
-
非平方数をCで印刷する
プログラムの説明 数の2乗は、その数にそれ自体を掛けたものです。 平方数または完全な正方形は、整数の2乗である整数です。 完全な平方は整数の平方です 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 これが1から100までのすべての完全な平方の平方根です。 √1 = 1 since 12 = 1 √4 = 2 since 22 = 4 √9 = 3 since 32 = 9 √16 = 4 since 42 = 16 √25 = 5 since 52 = 25 √36 = 6 since 6