當前位置:首頁 » 編程軟體 » 線程編程linux

線程編程linux

發布時間: 2022-07-13 14:47:41

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:

㈡ Linux多線程編程,替代sleep的幾種方式

我只想要進程的某個線程休眠一段時間的,可是用sleep()是將整個進程都休眠的,這個可能就達不到,我們想要的效果了。 目前我知道有三種方式:
1 usleep
這個是輕量級的, 聽說能可一實現線程休眠, 我個人並不喜歡這種方式,所以我沒有驗證它的可行信(個人不推薦)。
2 select
這個可以,我也用過這種方式, 它是在輪詢。
3 pthread_cond_timedwait

採用pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t *mutex, const struct timespec *abstime)可以優雅的解決該問題,設置等待條件變數cond,如果超時,則返回;如果等待到條件變數cond,也返回。本文暫不將內部機理,僅演示一個demo。
首先,看這段代碼,thr_fn為一個線程函數:
#include <stdio.h>#include <stdlib.h>int flag = 1;void * thr_fn(void * arg) {while (flag){printf("******\n");sleep(10);}printf("sleep test thread exit\n");}int main() {pthread_t thread;if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {printf("error when create pthread,%d\n", errno);return 1;}char c ;while ((c = getchar()) != 'q');printf("Now terminate the thread!\n");flag = 0;printf("Wait for thread to exit\n");pthread_join(thread, NULL);printf("Bye\n");return 0;}

輸入q後,需要等線程從sleep中醒來(由掛起狀態變為運行狀態),即最壞情況要等10s,線程才會被join。採用sleep的缺點:不能及時喚醒線程。
採用pthread_cond_timedwait函數實現的如下:
#include <stdio.h>#include <sys/time.h>#include <unistd.h>#include <pthread.h>#include <errno.h>static pthread_t thread;static pthread_cond_t cond;static pthread_mutex_t mutex;static int flag = 1;void * thr_fn(void * arg) {struct timeval now;struct timespec outtime;pthread_mutex_lock(&mutex);while (flag) {printf("*****\n");gettimeofday(&now, NULL);outtime.tv_sec = now.tv_sec + 5;outtime.tv_nsec = now.tv_usec * 1000;pthread_cond_timedwait(&cond, &mutex, &outtime);}pthread_mutex_unlock(&mutex);printf("cond thread exit\n");}int main(void) {pthread_mutex_init(&mutex, NULL);pthread_cond_init(&cond, NULL);if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {printf("error when create pthread,%d\n", errno);return 1;}char c ;while ((c = getchar()) != 'q');printf("Now terminate the thread!\n");pthread_mutex_lock(&mutex);flag = 0;pthread_cond_signal(&cond);pthread_mutex_unlock(&mutex);printf("Wait for thread to exit\n");pthread_join(thread, NULL);printf("Bye\n");return 0;}

pthread_cond_timedwait()函數阻塞住調用該函數的線程,等待由cond指定的條件被觸發(pthread_cond_broadcast() or pthread_cond_signal())。
當pthread_cond_timedwait()被調用時,調用線程必須已經鎖住了mutex。函數pthread_cond_timedwait()會對mutex進行【解鎖和執行對條件的等待】(原子操作)。這里的原子意味著:解鎖和執行條件的等待是原則的,一體的。(In this case, atomically means with respect to the mutex andthe condition variable and other access by threads to those objectsthrough the pthread condition variable interfaces.)
如果等待條件滿足或超時,或線程被取消,調用線程需要在線程繼續執行前先自動鎖住mutex,如果沒有鎖住mutex,產生EPERM錯誤。即,該函數返回時,mutex已經被調用線程鎖住。
等待的時間通過abstime參數(絕對系統時間,過了該時刻就超時)指定,超時則返回ETIMEDOUT錯誤碼。開始等待後,等待時間不受系統時鍾改變的影響。
盡管時間通過秒和納秒指定,系統時間是毫秒粒度的。需要根據調度和優先順序原因,設置的時間長度應該比預想的時間要多或者少點。可以通過使用系統時鍾介面gettimeofday()獲得timeval結構體。

㈢ Linux 的多線程編程的幾點注意事項

1、不要在子線程操作UI控制項
2、如果你操作了,也絕對不能調用UpdateData來更新界面,否則程序Crash
3、這一條建立在第一條基礎上---你在子線程操作UI控制項,不可以讓主線程等待某些條件(如等待子線程關閉,而子線程正在操作UI、等待進

入臨界區,而子線程已經進入,並且操作UI),否則會出現假死...
4、最好方案:子線程操作數據,完成之後,通知主線程進行更新....

㈣ 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多線程編程的實例介紹了,使用多線程編程還能夠改善程序結構,有興趣的朋友不妨試試看吧。

㈤ linux下多線程編程問題,求各種優化

while((p=fork())==-1);//創建進程
if(p==0)
{
ret=pthread_create(&id1,NULL,(void *)pthread1, NULL);//創建線程
if(ret!=0) perror("線程1創建失敗");
ret=pthread_create(&id2,NULL,(void *)pthread2, NULL);
if(ret!=0) perror("線程2創建失敗");
ret=pthread_create(&id3,NULL,(void *)pthread3, NULL);
if(ret!=0) perror("線程3創建失敗");

......
pthread_join(id1,NULL);
pthread_join(id2,NULL);
pthread_join(id3,NULL);
..........//結束線程
exit(0);
}

void pthread1(void *arg)
{
while(time(NULL) < time_flag) //可以在這里判斷總接入次數,現在是時間判斷
{
if(pthread_mutex_lock(&mutex)!=0)//鎖定數據 可以在這里判斷接入次數,現在是寫鎖定判斷
{
perror("鎖定失敗");
}
else printf("線程1:鎖定數據量\n");
{

}
if(pthread_mutex_unlock(&mutex)!=0) //數據解鎖 這里可以判斷不超過3次鎖定解鎖
{
perror("解鎖失敗");
}
else
printf("線程1:我已解鎖\n");
sleep(4);
}
}
其他的你自己補充吧,自己定義幾個全局變數控制線程鎖定解鎖邏輯關系就行

㈥ Linux 的多線程編程中,如何給線程發信號

不管是在進程還是線程,很多時候我們都會使用一些定時器之類的功能,這里就定時器在多線程的使用說一下。首先在linux編程中定時器函數有alarm()和setitimer(),alarm()可以提供一個基於秒的定時功能,而setitimer可以提供一個基於微妙的定時功能。

alarm()原型:
#include <unistd.h>
unsigned int alarm(unsigned int seconds);

這個函數在使用上很簡單,第一次調用這個函數的時候是設置定時器的初值,下一次調用是重新設置這個值,並會返回上一次定時的剩餘時間。

setitimer()原型:
#include <sys/time.h>
int setitimer(int which, const struct itimerval *value,struct itimerval *ovalue);

這個函數使用起來稍微有點說法,首先是第一個參數which的值,這個參數設置timer的計時策略,which有三種狀態分別是:

ITIMER_REAL:使用系統時間來計數,時間為0時發出SIGALRM信號,這種定時能夠得到一個精準的定時,當然這個定時是相對的,因為到了微秒級別我們的處理器本身就不夠精確。

ITIMER_VIRTUAL:使用進程時間也就是進程分配到的時間片的時間來計數,時間為0是發出SIGVTALRM信號,這種定時顯然不夠准確,因為系統給進程分配時間片不由我們控制。

ITIMER_PROF:上面兩種情況都能夠觸發

第二個參數參數value涉及到兩個結構體:

struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};

struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};

在結構體itimerval中it_value是定時器當前的值,it_interval是當it_value的為0後重新填充的值。而timeval結構體中的兩個變數就簡單了一個是秒一個是微秒。

上面是這兩個定時函數的說明,這個函數使用本不是很難,可以說是很簡單,但是碰到具體的應用的時候可能就遇到問題了,在多進程編程中使用一般不會碰到什麼問題,這里說的這些問題主要體現在多線程編程中。比如下面這個程序:

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

void sig_handler(int signo)
{
alarm(2);
printf("alarm signal\n");
}

void *pthread_func()
{
alarm(2);
while(1)
{
pause();
}
}

int main(int argc, char **argv)
{
pthread_t tid;
int retval;

signal(SIGALRM, sig_handler);

if((retval = pthread_create(&tid, NULL, pthread_func, NULL)) < 0)
{
perror("pthread_create");
exit(-1);
}

while(1)
{
printf("main thread\n");
sleep(10);
}
return 0;
}
這個程序的理想結果是:
main thread
alarm signal
alarm signal
alarm signal
alarm signal
alarm signal
main thread
可事實上並不是這樣的,它的結果是:
main pthread
alarm signal
main pthread
alarm signal
main pthread

㈦ Linux下如何實現shell多線程編程

程序代碼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:

㈧ 關於linux下多線程編程

pthread_join 線程停止等待函數沒有調用

pthread_create 線程生成後,沒有等子線程停止,主線程就先停止了。

主線程停止後,整個程序停止,子線程在沒有printf的時候就被結束了。

結論:不是你沒有看到結果,而是在子線程printf("..................\n");之前整個程序就已經停止了。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#define FALSE -1
#define TRUE 0

void *shuchu( void *my )
{
int j;
printf("..................\n");
}
int main()
{
int i = 0;
int rc = 0;
int ret1;
pthread_t p_thread1;
if(0!=(ret1 = pthread_create(&p_thread1, NULL, shuchu, NULL)))printf("sfdfsdfi\n");
printf("[%d]\n",p_thread1);
pthread_join(p_thread1, NULL);
return TRUE;

}

㈨ Linux中為什麼要使用多線程編程

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

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

熱點內容
官方源碼 發布:2025-02-08 14:09:25 瀏覽:435
python過濾器 發布:2025-02-08 14:05:06 瀏覽:615
火山幣演算法 發布:2025-02-08 14:04:49 瀏覽:668
jffs2解壓 發布:2025-02-08 13:55:15 瀏覽:388
如何向伺服器發送大數據包 發布:2025-02-08 13:55:12 瀏覽:662
伺服器pop地址是什麼 發布:2025-02-08 13:39:21 瀏覽:386
網站訪問計數器 發布:2025-02-08 13:32:07 瀏覽:6
釣魚的腥怎麼配置 發布:2025-02-08 13:22:57 瀏覽:754
php數組的引用 發布:2025-02-08 13:22:54 瀏覽:94
致遠a6伺服器地址在哪裡看 發布:2025-02-08 13:22:06 瀏覽:132