使用pthread_create()創建線程


可以通過 pthread_create()函數創建新線程。

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
							  const pthread_attr_t *restrict attr,
							  void *(*start_rtn)(void *),
							  void *restrict arg);

返回值:
若成功,返回0;否則,返回錯誤編碼

參數說明:

  • tidp:新創建的線程ID會被設置成tidp指向的內存單元。
  • attr:用於定制各種不能的線程屬性,默認為NULL
  • start_rtn:新創建的線程從start_rtn函數的地址開始運行,該函數只有一個void類型的指針參數即arg,如果start_rtn需要多個參數,可以將參數放入一個結構中,然后將結構的地址作為arg傳入。

pthread函數在調用失敗后通常會返回錯誤碼,但不會設置errno

我們看下面一個例子,該示例中,程序創建了一個線程,打印了進程ID、新線程的線程ID以及初始線程的線程ID。

#include <pthread.h>

pthread_t ntid;

void printids(const char *s)
{
	pid_t	pid;
	pthread_t	tid;
	
	pid = getpid();
	tid = pthread_self();

	printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid, (unsigned long)tid, (unsigned long)tid);
}

void* thr_fn(void *arg)
{
	printids("new thread:");
	return((void*)0);
}

int main()
{
	int 	err;
	
	err = pthread_create(&ntid, NULL, thr_fn, NULL);
	if(err!=0)
	{
		printf("can't create thread\n");
		exit(1);
	}
	printids("main thread:");
	sleep(2);
	exit(0);
}

運行結果如下:

main thread: pid 13019 tid 139937898653440 (0x7f45d4bd6700)
new thread: pid 13019 tid 139937890158336 (0x7f45d43bc700)

正如我們的期望,進程ID相同10310,線程ID不同。

主線程如果不休眠,有可能在新線程執行之前就退出了。

如下是去掉后的再次執行結果,很明顯,第一次執行時,新線程沒有機會運行:

➜  tmp ./pt
main thread: pid 13113 tid 139742167656192 (0x7f1842436700)
➜  tmp ./pt
main thread: pid 13119 tid 139768977393408 (0x7f1e803f8700)
new thread: pid new thread: pid 13119 tid 139768968922880 (0x7f1e7fbe4700)

上面示例中,我們使用pthread_self()函數獲得線程的ID


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM