當前位置:首頁 » 操作系統 » linux多線程實例

linux多線程實例

發布時間: 2022-02-20 18:32:43

A. linux下如何實現shell多線程編程以提高應用程序的響應

Linux中多線程編程擁有提高應用程序的響應、使多cpu系統更加有效等優點,下面小編將通過Linux下shell多線程編程的例子給大家講解下多線程編程的過程,一起來了解下吧。

#!/bin/bash

#———————————————————————————–

# 此例子說明了一種用wait、read命令模擬多線程的一種技巧

# 此技巧往往用於多主機檢查,比如ssh登錄、ping等等這種單進程比較慢而不耗費cpu的情況

# 還說明了多線程的控制

#———————————————————————————–

function a_sub

{

# 此處定義一個函數,作為一個線程(子進程)

sleep 3 # 線程的作用是sleep 3s

}

tmp_fifofile=「/tmp/$.fifo」 mkfifo $tmp_fifofile # 新建一個fifo類型的文件

exec 6《》$tmp_fifofile # 將fd6指向fifo類型

rm $tmp_fifofile thread=15 # 此處定義線程數

for

((i=0;i《$thread;i++));do echo

done 》&6 # 事實上就是在fd6中放置了$thread個回車符

for

((i=0;i《50;i++));do # 50次循環,可以理解為50個主機,或其他

read -u6 # 一個read -u6命令執行一次,就從fd6中減去一個回車符,然後向下執行,

# fd6中沒有回車符的時候,就停在這了,從而實現了線程數量控制

{ # 此處子進程開始執行,被放到後台

a_sub &&

{ # 此處可以用來判斷子進程的邏輯

echo 「a_sub is finished」

}

||

{ echo 「sub error」

}

echo 》&6 # 當進程結束以後,再向fd6中加上一個回車符,即補上了read -u6減去的那個

}

& done wait # 等待所有的後檯子進程結束

exec 6》&- # 關閉df6 exit 0

說明:

此程序中的命令

mkfifo tmpfile

和linux中的命令

mknod tmpfile p

效?果相同。區別是mkfifo為POSIX標准,因此推薦使用它。該命令創建了一個先入先出的管道文件,並為其分配文件標志符6。管道文件是進程之間通信的一種方式,注意這一句很重要

exec 6《》$tmp_fifofile # 將fd6指向fifo類型

如果沒有這句,在向文件$tmp_fifofile或者&6寫入數據時,程序會被阻塞,直到有read讀出了管道文件中的數據為止。而執行了上面這一句後就可以在程序運行期間不斷向fifo類型的文件寫入數據而不會阻塞,並且數據會被保存下來以供read程序讀出。

通過運行命令:

time 。/multithread.sh 》/dev/null

最終運算時間: 50/15 = 3組(每組15)+1組(5個《15 組成一個組)= 4組,每組花費時間:3秒,

則 3 * 4 = 12 秒。

傳統非多線程的代碼 運算時間: 50 * 3 = 150 秒。

上面就是Linux下shell多線程編程的實例介紹了,使用多線程編程還能夠改善程序結構,有興趣的朋友不妨試試看吧。

B. linux裡面多線程編程問題

mutex是線程鎖,多個線程運行,當遇到臨界資源,基本上是全局變數時,需要順序的操作這些資源,不能都去操作,就像資料庫裡面的原子操作,所以需要用一個鎖來同步這些線程,讓他們一個一個的來,誰獲得鎖,誰有權操作。

pthread_mutex_init是對鎖進行初始化,一個參數是鎖結構體,一個是屬性,屬性基本為NULL就行。

pthread_mutex_lock用來加鎖,加鎖後,別的線程運行到這個地方就不能繼續運行了,等待解鎖。

pthread_mutex_unlock用來解鎖。

pthread_mutex_destroy用來銷毀鎖。

C. LINUX多線程求解,列題是華清遠見上面的,代碼如下,利用線程互斥鎖實現線程的同步

目測是線程退出時沒有解開互斥鎖,導致其它線程一直在等互斥鎖被解開。

以下是修改後的thrd_func函數代碼:

//線程函數入口
void*thrd_func(void*arg)
{
intthrd_num=(int)arg;
intdelay_time=0;
intcount=0;
intres;

res=pthread_mutex_lock(&mutex);//互斥鎖上鎖
if(res)
{
printf("Thread%dlockfailed ",thrd_num);
pthread_exit(NULL);
}

printf("Thread%disstarting ",thrd_num);

for(count=0;count<REPEAT_NUMBER;count++)
{
delay_time=(int)(rand()%5);//隨機時間數
sleep(delay_time);
printf(" Thread%d:job%ddelay=%d ",thrd_num,count,delay_time);
}

pthread_mutex_unlock(&mutex);//解開互斥鎖

printf("Thread%dfinished ",thrd_num);
pthread_exit(NULL);
}

D. linux下多進程或者多線程編程的問題。新手,望指教!

你好,多進程或多線程,都不會阻塞當前語句代碼。為了您的理解,我就大膽舉下面兩個例子:
多進程:你可以看成是本來是一條路的,現在從中間拆成兩條,然後每一條路都有屬於自己這條路的代碼在運行。
多線程:你可以看成是一條路,然後分出車道,比如左車道和右車道甚至是停車道,然後每條車道都單獨通車,其他車道的不能對這條車道進行干擾。

所以,把一條路從中間拆成兩條,成本是很高的。但是把一條路分車道,成本就不是很高了。
對於您提出的main函數的疑問,當main函數最後執行完畢,程序退出後,所有的進程包括線程,都會被關閉的,哪怕你的程序中沒有關閉,操作系統也會幫你關閉的,現在的操作系統都非常的完善了。當然,也存在有線程或進程不被釋放的特殊情況,最好在編程中要記得釋放。

E. Linux多線程編程

程序代碼test.c共兩個線程,一個主線程,一個讀緩存區的線程:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char globe_buffer[100];

void *read_buffer_thread(void *arg); //這里先聲明一下讀緩存的線程,具體實現寫在後面了

int main()
{
int res,i;
pthread_t read_thread;
for(i=0;i<20;i++)
globe_buffer[i]=i;
printf("\nTest thread : write buffer finish\n");
sleep(3);\\這里的3秒是多餘,可以不要。
res = pthread_create(&read_thread, NULL, read_buffer_thread, NULL);
if (res != 0)
{
printf("Read Thread creat Error!");
exit(0);
}
sleep(1);
printf("waiting for read thread to finish...\n");

res = pthread_join(read_thread, NULL);
if (res != 0)
{
printf("read thread join failed!\n");
exit(0);
}
printf("read thread test OK, have fun!! exit ByeBye\n");
return 0;
}
void *read_buffer_thread(void *arg)
{
int i,x;
printf("Read buffer thread read data : \n");
for(i=0;i<20;i++)
{
x=globe_buffer[i];
printf("%d ",x);
globe_buffer[i]=0;//清空
}
printf("\nread over\n");
}
---------------------------------------------------------------------------------
以上程序編譯
gcc -D_REENTRANT test.c -o test.o –lpthread
運行這個程序:
$ ./test.o:

F. linux怎麼創建多線程

線程是「進程」中某個單一順序的控制流。也被稱為輕量進程。在POSIX線程中,線程體是一個函數。用pthread_create函數來啟動這個線程。用pthread_join函數來等待線程結束。在linux中可以通過posix實現

G. java的多線程與linux的多線程的關系

java自己實現了線程庫,也就是說java的線程並不和操作系統的線程對應,jvm在操作系統上面是一個進程,當這個進程被操作系統調度到後,jvm內部實現的線程庫再調度java線程,為什麼是這樣呢?考慮到以前的操作系統內核,比如linux,在以前都不直接支持線程,用戶線程和內核線程是多對一的關系,solaris一度也是這樣,所以java當然心有餘而力不足了,你操作系統都不能完美支持線程,你讓我實現不是難為我嗎?在那個年代,java多線程的調度完全是自主的,操作系統根本不知道java是多線程的,調度策略完全自己實現,單cpu下肯定是分時的,多cpu下就看jvm會不會建立多cpu上的多jvm實例了。
到了後來,操作系統內核紛紛都支持了多線程(windows開始就支持),那麼java也要考慮推卸一些責任了,這樣java線程就和操作系統線程一一對應或多多對應了,這個時候,如果是一一對應,那麼線程的調度完全交給了操作系統內核,當然jvm還保留一些策略足以影響到其內部的線程調度,舉個例子,在linux下,只要一個Thread.run就會調用一個fork產生一個線程。
問:java獲得cup使用權採用的搶占機制,使用cup的時候是分時機制,這句話對不對?
答:部分對,早期實現,基本可以實現搶占式,但是現代實現,如果系統不支持搶占,那麼jvm也無所謂搶佔了。
問:多線程使用cup和使用的操作系統有關還是java機制有關(xp是什麼機制)
答:早期是java機制實現,現在大部分是操作系統實現的,java機制僅僅保留了相關策略從而影響調度;xp是基於優先順序的搶占式調度,其性能很大程度依賴於動態優先順序提升

H. C++在linux下怎麼多線程

#ifndefTHREAD_H_
#defineTHREAD_H_
#include<unistd.h>
#include<pthread.h>
classRunnable
{
public:
//運行實體
virtualvoidrun()=0;
};
//線程類
classThread:publicRunnable
{
private:
//線程初始化號
staticintthread_init_number;
//當前線程初始化序號
intcurrent_thread_init_number;
//線程體
Runnable*target;
//當前線程的線程ID
pthread_ttid;
//線程的狀態
intthread_status;
//線程屬性
pthread_attr_tattr;
//線程優先順序
sched_paramparam;
//獲取執行方法的指針
staticvoid*run0(void*pVoid);
//內部執行方法
void*run1();
//獲取線程序號
staticintget_next_thread_num();
public:
//線程的狀態-新建
staticconstintTHREAD_STATUS_NEW=0;
//線程的狀態-正在運行
staticconstintTHREAD_STATUS_RUNNING=1;
//線程的狀態-運行結束
staticconstintTHREAD_STATUS_EXIT=-1;
//構造函數
Thread();
//構造函數
Thread(Runnable*target);
//析構
~Thread();
//線程的運行體
voidrun();
//開始執行線程
boolstart();
//獲取線程狀態
intget_state();
//等待線程直至退出
voidjoin();
//等待線程退出或者超時
voidjoin(unsignedlongmillis_time);
//比較兩個線程時候相同,通過current_thread_init_number判斷
booloperator==(constThread*other_pthread);
//獲取this線程ID
pthread_tget_thread_id();
//獲取當前線程ID
staticpthread_tget_current_thread_id();
//當前線程是否和某個線程相等,通過tid判斷
staticboolis_equals(Thread*iTarget);
//設置線程的類型:綁定/非綁定
voidset_thread_scope(boolisSystem);
//獲取線程的類型:綁定/非綁定
boolget_thread_scope();
//設置線程的優先順序,1-99,其中99為實時,意外的為普通
voidset_thread_priority(intpriority);
//獲取線程的優先順序
intget_thread_priority();
};
intThread::thread_init_number=1;
inlineintThread::get_next_thread_num()
{
returnthread_init_number++;
}
void*Thread::run0(void*pVoid)
{
Thread*p=(Thread*)pVoid;
p->run1();
returnp;
}
void*Thread::run1()
{
thread_status=THREAD_STATUS_RUNNING;
tid=pthread_self();
run();
thread_status=THREAD_STATUS_EXIT;
tid=0;
pthread_exit(NULL);
}
voidThread::run()
{
if(target!=NULL)
{
(*target).run();
}
}
Thread::Thread()
{
tid=0;
thread_status=THREAD_STATUS_NEW;
current_thread_init_number=get_next_thread_num();
pthread_attr_init(&attr);
}
Thread::Thread(Runnable*iTarget)
{
target=iTarget;
tid=0;
thread_status=THREAD_STATUS_NEW;
current_thread_init_number=get_next_thread_num();
pthread_attr_init(&attr);
}
Thread::~Thread()
{
pthread_attr_destroy(&attr);
}
boolThread::start()
{
returnpthread_create(&tid,&attr,run0,this);
}
inlinepthread_tThread::get_current_thread_id()
{
returnpthread_self();
}
inlinepthread_tThread::get_thread_id()
{
returntid;
}
inlineintThread::get_state()
{
returnthread_status;
}
voidThread::join()
{
if(tid>0)
{
pthread_join(tid,NULL);
}
}
voidThread::join(unsignedlongmillis_time)
{
if(tid==0)
{
return;
}
if(millis_time==0)
{
join();
}
else
{
unsignedlongk=0;
while(thread_status!=THREAD_STATUS_EXIT&&k<=millis_time)
{
usleep(100);
k++;
}
}
}
boolThread::operator==(constThread*other_pthread)
{
if(other_pthread==NULL)
{
returnfalse;
}if(current_thread_init_number==(*other_pthread).current_thread_init_number)
{
returntrue;
}
returnfalse;
}
boolThread::is_equals(Thread*iTarget)
{
if(iTarget==NULL)
{
returnfalse;
}
returnpthread_self()==iTarget->tid;
}
voidThread::set_thread_scope(boolisSystem)
{
if(isSystem)
{
pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
}
else
{
pthread_attr_setscope(&attr,PTHREAD_SCOPE_PROCESS);
}
}
voidThread::set_thread_priority(intpriority)
{
pthread_attr_getschedparam(&attr,&param);
param.__sched_priority=priority;
pthread_attr_setschedparam(&attr,&param);
}
intThread::get_thread_priority(){
pthread_attr_getschedparam(&attr,&param);
returnparam.__sched_priority;
}
#endif/*THREAD_H_*/

I. 在Linux環境下,對一個設備文件進行多線程讀寫(兩個線程就行),求大神給一個簡單的程序。

配置文件為 conf.txt
測試代碼如下,注意鏈接的時候加上 -lpthread 這個參數

#include <stdio.h>
#include <errno.h> //perror()
#include <pthread.h>

#include <unistd.h> //sleep()
#include <time.h> // time()
#include <stdlib.h> //rand()

#define FD "conf.txt"

typedef void *(*fun)(void *);

struct my_struct
{
unsigned time_to_wait;
int n;
};

void *test_thread(struct my_struct *);

int main (int argc, char const *argv[])
{
FILE *fp = fopen(FD, "r");
if (fp == NULL)
{
perror(FD);
return -1;
}

srand((unsigned)time(NULL)); //初始化隨機種子

int thread_count;
fscanf(fp, "%d", &thread_count);
fclose(fp);

if (thread_count <= 0)
{
printf("線程數<1,退出程序。\n");
return -1;
}

pthread_t *ptid = (pthread_t *)malloc(sizeof(pthread_t) * thread_count); //保存線程ID

int i;
for (i = 0; i < thread_count; i++)
{
int tw = rand() % thread_count + 1; //隨機等待時間

struct my_struct * p = (struct my_struct *)malloc(sizeof(struct my_struct));
if (p == NULL)
{
perror("內存分配錯誤");
goto ERROR;
}
p->time_to_wait = tw;
p->n = i + 1;

int rval = pthread_create(ptid + i, NULL, (fun) test_thread, (void *)(p)); //注意這里的強制轉換(兩個)
if (rval != 0)
{
perror("Thread creation failed");
goto ERROR;
}
//sleep(1); //這句加也可以,不加也可以。最開始的時候加上這個是為了讓兩個線程啟動的時候之間有一定的時間差
}

printf("主線程啟動\n\n");
fflush(stdout);
for (i = 0; i < thread_count; i++)
{
pthread_join(*(ptid + i), NULL); //等待所有線程退出。
}
printf("\n主線程退出\n");
ERROR:
free(ptid);
return 0;
}

void *test_thread(struct my_struct * p) //線程啟動的時候運行的函數
{
printf("第%d個線程啟動,預計運行%d秒\n", p->n, p->time_to_wait);
fflush(stdout);

sleep(p->time_to_wait); //讓線程等待一段時間
printf("第%d個線程結束\n", p->n);
fflush(stdout);
free(p);
return NULL;
}

你的第二個問題我在網路HI回你了~

J. linux 編寫一個多線程程序,要求主線程創建3個子線程,3個子線程在執行時都修改一個他們的共享變數。

void func1(int n)
{
printf("%d",n*10);
}
void func1(int n)
{
printf("%d",n-10);
}

void func1(int n)
{
printf("%d",n/2);
}

int main(void)
{
int n = 10;
pthread_t 1_thread,2_thread,3_thread;
pthread_create(1_thread,NULL,func1,n);
pthread_create(2_thread,NULL,func2,n);
pthread_create(3_thread,NULL,func3,n);
return 0;
}

熱點內容
單片機android 發布:2024-09-20 09:07:24 瀏覽:763
如何提高三星a7安卓版本 發布:2024-09-20 08:42:35 瀏覽:662
如何更換伺服器網站 發布:2024-09-20 08:42:34 瀏覽:309
子彈演算法 發布:2024-09-20 08:41:55 瀏覽:287
手機版網易我的世界伺服器推薦 發布:2024-09-20 08:41:52 瀏覽:815
安卓x7怎麼邊打游戲邊看視頻 發布:2024-09-20 08:41:52 瀏覽:160
sql資料庫安全 發布:2024-09-20 08:31:32 瀏覽:91
蘋果連接id伺服器出錯是怎麼回事 發布:2024-09-20 08:01:07 瀏覽:505
編程鍵是什麼 發布:2024-09-20 07:52:47 瀏覽:655
學考密碼重置要求的證件是什麼 發布:2024-09-20 07:19:46 瀏覽:479