- Linux下線程是在進程的地址空間內運行的,線程擁有進程的一部分資源與代碼,是進程的一個執行分支
- 線程是cpu的基本調度單位
- 進程是承擔資源分配的基本單位
- Linux下進程被稱爲輕量級進程
- Linux下無真正意義的線程,線程是用進程模擬實現的
測試代碼:
#include<stdio.h>
#include<pthread.h>
int i = 0;
void *pthread1(void *arg)
{
while(1)
{
sleep(1);
printf("線程一:running\n");
if(i++ > 5)
{
printf("線程一退出\n");
break;
}
}
}
void *pthread2(void *arg)
{
while(1)
{
sleep(2);
printf("線程二:running\n");
}
}
void *pthread3(void *arg)
{
while(3)
{
sleep(2);
printf("線程三:running\n");
}
}
int main()
{
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_create(&thread1, NULL, pthread1, NULL);
pthread_create(&thread2, NULL, pthread2, NULL);
pthread_create(&thread3, NULL, pthread3, NULL);
pthread_join(thread1, NULL); //線程1,設置爲被等待
if(0 == pthread_cancel(thread2))//線程2,被主線取消,一旦運行在這塊,線程2就結束了
{
printf("線程二被主線程取消\n");
}
if(0 == pthread_detach(thread3)) //線程3,被主線程設置爲可分離狀態
{
printf("線程三被主線程設置爲可分離狀態\n");
}
sleep(3);//在睡眠的3秒中,只有線程3在運行
}
運行結果:
zhi