1、參考學習大神網址:http://blog.csdn.net/ithomer/article/details/6063067
#include<stdio.h> #include<pthread.h> #include<string.h> #include<sys/types.h> #include<unistd.h> pthread_t main_tid; void *func(void *arg) { while(1) { printf("子線程:Hello,world!\r\n"); sleep(2); } } int main() { int err; err = pthread_create(&main_tid, NULL, func, NULL); //創建線程 if(err != 0) { printf("create thread error: %s/n",strerror(err)); return 1; } printf("main thread: pid: %u tid: %u (0x%x)/n", (unsigned int)getpid(), (unsigned int)pthread_self(), (unsigned int)pthread_self()); /* while(1) { printf("主線程:Hello,world!\r\n"); sleep(2); } */ return 0; }
函數一:pthread_create
函數聲明
int pthread_create(pthread_t *restrict_tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
返回值
若成功則返回0,否則返回出錯編號!!!
參數
pthread_t *restrict_tidp: 第一個參數為指向線程標識符的指針。
const pthread_attr_t *restrict_attr: 第二個參數用來設置線程屬性。
void*(*start_rtn)(void*): 第三個參數是線程運行函數的起始地址。
void *restrict arg: 最后一個參數是運行函數的參數。
另外
在編譯時注意加上-lpthread參數,以調用靜態鏈接庫。因為pthread並非Linux系統的默認庫.
函數二:strerror(int errnum)
errnum:錯誤標號,通常用errno(標准錯誤號,定義在errno.h中)
通過標准錯誤的標號,獲得錯誤的描述字符串 ,將單純的錯誤標號轉為字符串描述,方便用戶查找錯誤。
函數三:getpid()
返回值:目前進程的進程ID
函數四:pthread_self函數作用:獲得線程自身的ID。
函數五: sleep,類似FreeRTOS的vTaskDelay
-
- sleep的精度是秒
- usleep的精度是微妙,不精確
Makefile:編寫如下:
# 參考大神博客地址:http://blog.csdn.net/haoel/article/details/2887 # http://www.cnblogs.com/sld666666/archive/2010/04/08/1707789.html # 為每一個 *.c文件生成 *o文件。 # 連接每一個*.o文件,生成可執行文件。 # make 過程 如下 # 1、make會在當前目錄下找名字叫“Makefile”或“makefile”的文件。 # 2、如果找到,它會找文件中的第一個目標文件(target),在上面的例子中,他會找到“edit”這個文件,並把這個文件作為最終的目標文件。 # 3、如果edit文件不存在,或是edit所依賴的后面的 .o 文件的文件修改時間要比edit這個文件新,那么,他就會執行后面所定義的命令來生成edit這個文件。 # 4、如果edit所依賴的.o文件也存在,那么make會在當前文件中找目標為.o文件的依賴性,如果找到則再根據那一個規則生成.o文件。(這有點像一個堆棧的過程) # 5、當然,你的C文件和H文件是存在的啦,於是make會生成 .o 文件,然后再用 .o 文件生命make的終極任務,也就是執行文件edit了。 # 根據Makefile 的過程1。應該第一步:在所在的thread.c 文件路徑下,新建一個文件名字為 Makefile”或“makefile”的文件。 # 根據Makefile 的過程2、3。應該第二步:用 vim 打開 Makefile文件,第一行寫代碼 edit : thread.o edit:thread.o #可執行文件edit 由 thread.o 組成(對Makefile來說 這個edit 就是最終的目標文件,即執行文件) gcc -o edit thread.o # 這句代碼的意思是:將thread.o連接成可執行的二進制文件edit 參考GCC語法:http://blog.csdn.net/tomatofly/article/details/6035363 thread.o:thread.c # 這句代碼的意思是:thread.o依賴關系是 thread.c 和 stdio.h 兩個文件,也就是說 如果這兩個文件有一個改動的,thread.o就會被重新編譯 gcc -c thread.c # 這句代碼的意思是:只編譯thread.c,成功時輸出目標文件thread.o 參考GCC語法:http://blog.csdn.net/tomatofly/article/details/6035363
