1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語 POSIX ThreadでSleep Sort

Posted at

ネタ的なソートアルゴリズムとして知られるSleep Sort。Qiitaでも様々な言語で実装した記事が公開されています。ということでマルチスレッドの練習も兼ねて、C言語のPOSIX Threadライブラリを使って実装してみました。

sleepSort.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define N 10

void *sort(void *t){
	int n = *(int *)t;
	sleep(n);
	printf("%d\n", n);
	pthread_exit(NULL);
}

int main(void){
	int arr[N] = {2,7,10,6,4,5,8,3,9,1};
	pthread_t tid[N];
	for(int i=0; i<N; i++){
		if(pthread_create(&tid[i], NULL, sort, &arr[i])){
			fprintf(stderr, "error: pthread_create\n");
			exit(1);
		}
	}
	for(int i=0; i<N; i++){
		if(pthread_join(tid[i], NULL)){
			fprintf(stderr, "error: pthread_join\n");
			exit(1);
		}
	}
	return 0;
}

以下のようにコンパイル、実行できます。

$ gcc -pthread -Wall sleepSort.c 
$ ./a.out 
1
2
3
4
5
6
7
8
9
10

10秒かかりますが無事にソートされました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?