10
15

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 5 years have passed since last update.

pthreadの使い方

Last updated at Posted at 2019-05-16

はじめに

pthreadの使い方

ソース

pthread_create()でスレッドを作る

スレッドの処理の終了を待ちたいときはpthread_join()
待たないときはpthread_detach()
どちらか必ず呼ぶ

main.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_func(void *param);

int main(void) {

	pthread_t thread;
	int ret = 0;

	// スレッドの作成
	// int pthread_create(pthread_t * thread, pthread_attr_t * attr,
	//                    void * (*start_routine)(void *), void * arg)
	// 第4引数に渡した値が、スレッド関数の引数に渡される
	ret = pthread_create(&thread, NULL, thread_func, NULL);
	if (ret != 0) {
		// pthread_createが失敗した場合は0以外の値を返す
		exit(1);
	}

	// スレッドの終了を待機
	// int pthread_join(pthread_t th, void **thread_return)
	ret = pthread_join(thread, NULL);
	if (ret != 0) {
		// pthread_joinが失敗した場合は0以外の値を返す
		exit(1);
	}

	/*
	// スレッドの終了を待たない
	// int pthread_detach(pthread_t th)
	ret = pthread_detach(thread);
	if (ret != 0) {
		// pthread_detachが失敗した場合は0以外の値を返す
		exit(1);
	}
	*/

	return EXIT_SUCCESS;
}

void *thread_func(void *param)
{
	// 非同期に実行する処理
}
10
15
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
10
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?