Linux線程之建立(十)
- 1.線程的建立
- 2.參考代碼
1.線程的建立
功能:
建立一個線程。
參數:
thread:線程辨別符位址。
attr:線程屬性結構體位址,通常設定為 NULL。
start_routine:線程函數的入口位址。
arg:傳給線程函數的參數。
傳回值:
成功:0
失敗: 非0
在一個線程中調用pthreadcreate()建立新的線程後,目前線程從pthreadcreate()傳回繼續往下執行,而新的線程所執行的代碼由我們傳給pthreadcreate的函數指針startroutine決定。 由于pthread_create的錯誤碼不儲存在errno中,是以不能直接用perror()列印錯誤資訊,可以先用strerror()把錯誤碼轉換成錯誤資訊再列印。
2.參考代碼
//=============================================================================
// File Name : thread_create.c
// Author : FengQQ
//
// Description : 建立線程
// Annotation :
//
// Created by FengQQ. 2020-10-04
//=============================================================================
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
static int num = 0;
//---------------線程1入口函數---------------
void *pthread1_callback(void *arg)
{
while(1)
{
num++;
printf("I am thread1 run...\r\n");
sleep(1);
}
}
//---------------線程2入口函數---------------
void *pthread2_callback(void *arg)
{
while(1)
{
printf("I am thread2 run num:%d\r\n",num);
sleep(1);
}
}
int main(int argc,char * argv[])
{
pthread_t ptid1,ptid2;
int err;
err = pthread_create(&ptid1,NULL,pthread1_callback,NULL); //建立線程1
if(err != 0)
{
printf("create new pthread1 failed...\r\n");
return -1;
}
err = pthread_create(&ptid2,NULL,pthread2_callback,NULL); //建立線程2
if(err != 0)
{
printf("create new pthread2 failed...\r\n");
return -1;
}
printf("main pthread...\r\n");
sleep(2);
return 0;
}
Linux線程之回收資源(十一)
連結: link.(https://blog.csdn.net/qq_39721016/article/details/120239822)