http://www.aiuxian.com/article/p-1286301.html
2014
多線(xiàn)程和多進(jìn)程還是有很多區別的。其中之一就是,多進(jìn)程是linux內核本身所支持的,而多線(xiàn)程則需要相應的動(dòng)態(tài)庫進(jìn)行支持。對于進(jìn)程而言,數據之間都是相互隔離的,而多線(xiàn)程則不同,不同的線(xiàn)程除了堆??臻g之外所有的數據都是共享的。說(shuō)了這么多,我們還是自己編寫(xiě)一個(gè)多線(xiàn)程程序看看結果究竟是怎么樣的。
[cpp]
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
void func_1(void* args)
{
while(1){
sleep(1);
printf("this is func_1!\n");
}
}
void func_2(void* args)
{
while(1){
sleep(2);
printf("this is func_2!\n");
}
}
int main()
{
pthread_t pid1, pid2;
if(pthread_create(&pid1, NULL, func_1, NULL))
{
return -1;
}
if(pthread_create(&pid2, NULL, func_2, NULL))
{
return -1;
}
while(1){
sleep(3);
}
return 0;
}
和我們以前編寫(xiě)的程序有所不同,多線(xiàn)程代碼需要這樣編譯,輸入gcc thread.c -o thread -lpthread,編譯之后你就可以看到thread可執行文件,輸入./thread即可。
[cpp]
[test@localhost Desktop]$ ./thread
this is func_1!
this is func_2!
this is func_1!
this is func_1!
this is func_2!
this is func_1!
this is func_1!
this is func_2!
this is func_1!
this is func_1!
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。