c語言線程間通信,c++線程間通信的幾種方法

本文目錄一覽:

C語言中的MPI編程和多線程有什麼區別,MPI編程中針對的是一台電腦多核還是多台電腦?謝謝!

MPI(MPI是一個標準,有不同的具體實現,比如MPICH等)是多主機聯網協作進行並行計算的工具,當然也可以用於單主機上多核/多CPU的並行計算,不過效率低。它能協調多台主機間的並行計算,因此並行規模上的可伸縮性很強,能在從個人電腦到世界TOP10的超級計算機上使用。缺點是使用進程間通信的方式協調並行計算,這導致並行效率較低、內存開銷大、不直觀、編程麻煩。OpenMP是針對單主機上多核/多CPU並行計算而設計的工具,換句話說,OpenMP更適合單台計算機共享內存結構上的並行計算。由於使用線程間共享內存的方式協調並行計算,它在多核/多CPU結構上的效率很高、內存開銷小、編程語句簡潔直觀,因此編程容易、編譯器實現也容易(現在最新版的C、C++、Fortran編譯器基本上都內置OpenMP支持)。不過OpenMP最大的缺點是只能在單台主機上工作,不能用於多台主機間的並行計算!如果要多主機聯網使用OpenMP(比如在超級計算機上),那必須有額外的工具幫助,比如MPI+OpenMP混合編程。或者是將多主機虛擬成一個共享內存環境(Intel有這樣的平台),但這麼做效率還不如混合編程,唯一的好處是編程人員可以不必額外學習MPI編程。

用C語言如何實現多線程同時運行的情況下,各個線程輸出不同的隨機數?

1、使用pthread庫執行多線程,這個是Linux下的線程庫 Windows下應該有自己的API,不過這種東西一般還是以Linux為標準。pthread_create()創建一個線程,傳入fun()的函數指針就行了。然後這個Beep()的需求要進行線程間通信,可以用共享內存的方法,設一個bool變數flag共享,然後beep的時候設為false,beep完設成true。fun()裡面每次看一下這個flag,是false的話就不做動作等下一秒,基本可以滿足需求。

2、常式:

#include pthread.h

#include stdio.h

#include sys/time.h

#include string.h

#define MAX 10

pthread_t thread[2];

pthread_mutex_t mut;

int number=0, i;

void *thread1()

{

printf (“thread1 : I’m thread 1\n”);

for (i = 0; i  MAX; i++)

{

printf(“thread1 : number = %d\n”,number);

pthread_mutex_lock(mut);

number++;

pthread_mutex_unlock(mut);

sleep(2);

}

printf(“thread1 :主函數在等我完成任務嗎?\n”);

pthread_exit(NULL);

}

void *thread2()

{

printf(“thread2 : I’m thread 2\n”);

for (i = 0; i  MAX; i++)

{

printf(“thread2 : number = %d\n”,number);

pthread_mutex_lock(mut);

number++;

pthread_mutex_unlock(mut);

sleep(3);

}

printf(“thread2 :主函數在等我完成任務嗎?\n”);

pthread_exit(NULL);

}

void thread_create(void)

{

int temp;

memset(thread, 0, sizeof(thread)); //comment1

/*創建線程*/

if((temp = pthread_create(thread[0], NULL, thread1, NULL)) != 0) //comment2

printf(“線程1創建失敗!\n”);

else

printf(“線程1被創建\n”);

if((temp = pthread_create(thread[1], NULL, thread2, NULL)) != 0) //comment3

printf(“線程2創建失敗”);

else

printf(“線程2被創建\n”);

}

void thread_wait(void)

{

/*等待線程結束*/

if(thread[0] !=0) { //comment4

pthread_join(thread[0],NULL);

printf(“線程1已經結束\n”);

}

if(thread[1] !=0) { //comment5

pthread_join(thread[1],NULL);

printf(“線程2已經結束\n”);

}

}

int main()

{

/*用默認屬性初始化互斥鎖*/

pthread_mutex_init(mut,NULL);

printf(“我是主函數哦,我正在創建線程,呵呵\n”);

thread_create();

printf(“我是主函數哦,我正在等待線程完成任務阿,呵呵\n”);

thread_wait();

return 0;

}

c語言實例,linux線程同步的信號量方式 謝謝

這麼高的懸賞,實例放後面。信號量(sem),如同進程一樣,線程也可以通過信號量來實現通信,雖然是輕量級的。信號量函數的名字都以”sem_”打頭。線程使用的基本信號量函數有四個。

     信號量初始化。

     int sem_init (sem_t *sem , int pshared, unsigned int value);

    這是對由sem指定的信號量進行初始化,設置好它的共享選項(linux 只支持為0,即表示它是當前進程的局部信號量),然後給它一個初始值VALUE。

    等待信號量。給信號量減1,然後等待直到信號量的值大於0。

    int sem_wait(sem_t *sem);

    釋放信號量。信號量值加1。並通知其他等待線程。

    int sem_post(sem_t *sem);

    銷毀信號量。我們用完信號量後都它進行清理。歸還佔有的一切資源。

    int sem_destroy(sem_t *sem);

#include stdlib.h  

    #include stdio.h  

    #include unistd.h  

    #include pthread.h  

    #include semaphore.h  

    #include errno.h  

    #define return_if_fail(p) if((p) == 0){printf (“[%s]:func error!/n”, __func__);return;}  

    typedef struct _PrivInfo  

    {  

        sem_t s1;  

        sem_t s2;  

        time_t end_time;  

    }PrivInfo;  

    static void info_init (PrivInfo* thiz);  

    static void info_destroy (PrivInfo* thiz);  

    static void* pthread_func_1 (PrivInfo* thiz);  

    static void* pthread_func_2 (PrivInfo* thiz);  

    int main (int argc, char** argv)  

    {  

        pthread_t pt_1 = 0;  

        pthread_t pt_2 = 0;  

        int ret = 0;  

        PrivInfo* thiz = NULL;  

        thiz = (PrivInfo* )malloc (sizeof (PrivInfo));  

        if (thiz == NULL)  

        {  

            printf (“[%s]: Failed to malloc priv./n”);  

            return -1;  

        }  

        info_init (thiz);  

        ret = pthread_create (pt_1, NULL, (void*)pthread_func_1, thiz);  

        if (ret != 0)  

        {  

            perror (“pthread_1_create:”);  

        }  

        ret = pthread_create (pt_2, NULL, (void*)pthread_func_2, thiz);  

        if (ret != 0)  

        {  

            perror (“pthread_2_create:”);  

        }  

        pthread_join (pt_1, NULL);  

        pthread_join (pt_2, NULL);  

        info_destroy (thiz);  

        return 0;  

    }  

    static void info_init (PrivInfo* thiz)  

    {  

        return_if_fail (thiz != NULL);  

        thiz-end_time = time(NULL) + 10;  

        sem_init (thiz-s1, 0, 1);  

        sem_init (thiz-s2, 0, 0);  

        return;  

    }  

    static void info_destroy (PrivInfo* thiz)  

    {  

        return_if_fail (thiz != NULL);  

        sem_destroy (thiz-s1);  

        sem_destroy (thiz-s2);  

        free (thiz);  

        thiz = NULL;  

        return;  

    }  

    static void* pthread_func_1 (PrivInfo* thiz)  

    {  

        return_if_fail(thiz != NULL);  

        while (time(NULL)  thiz-end_time)  

        {  

            sem_wait (thiz-s2);  

            printf (“pthread1: pthread1 get the lock./n”);  

            sem_post (thiz-s1);  

            printf (“pthread1: pthread1 unlock/n”);  

            sleep (1);  

        }  

        return;  

    }  

    static void* pthread_func_2 (PrivInfo* thiz)  

    {  

        return_if_fail (thiz != NULL);  

        while (time (NULL)  thiz-end_time)  

        {  

            sem_wait (thiz-s1);  

            printf (“pthread2: pthread2 get the unlock./n”);  

            sem_post (thiz-s2);  

            printf (“pthread2: pthread2 unlock./n”);  

            sleep (1);  

        }  

        return;  

    }

線程之間如何共享socket?用C語言

你的意思是線程之間共用一個socket嗎,如果是,那比較容易,在主進程內定義一個socket變數,那麼在任何一個線程內都是可見的,其實這也是線程比進程間通信更加方便的原因。

linux下c的兩個進程如何實現通信?一個進程給另一個進程發送消息,另一個接受並顯示出來。求大神啊

linux中的進程通信分為三個部分:低級通信,管道通信和進程間通信IPC(inter process communication)。linux的低級通信主要用來傳遞進程的控制信號——文件鎖和軟中斷信號機制。linux的進程間通信IPC有三個部分——①信號量,②共享內存和③消息隊列。以下是我編寫的linux進程通信的C語言實現代碼。操作系統為redhat9.0,編輯器為vi,編譯器採用gcc。下面所有實現代碼均已經通過測試,運行無誤。

一.低級通信–信號通信

signal.c

#include signal.h

#include stdio.h

#include unistd.h

/*捕捉到信號sig之後,執行預先預定的動作函數*/

void sig_alarm(int sig)

{

printf(“—the signal received is %d. /n”, sig);

signal(SIGINT, SIG_DFL); //SIGINT終端中斷信號,SIG_DFL:恢復默認行為,SIN_IGN:忽略信號

}

int main()

{

signal(SIGINT, sig_alarm);//捕捉終端中斷信號

while(1)

{

printf(“waiting here!/n”);

sleep(1);

}

return 0;

}

二.管道通信

pipe.c

#include stdio.h

#define BUFFER_SIZE 30

int main()

{

int x;

int fd[2];

char buf[BUFFER_SIZE];

char s[BUFFER_SIZE];

pipe(fd);//創建管道

while((x=fork())==-1);//創建管道失敗時,進入循環

/*進入子進程,子進程向管道中寫入一個字元串*/

if(x==0)

{

sprintf(buf,”This is an example of pipe!/n”);

write(fd[1],buf,BUFFER_SIZE);

exit(0);

}

/*進入父進程,父進程從管道的另一端讀出剛才寫入的字元串*/

else

{

wait(0);//等待子進程結束

read(fd[0],s,BUFFER_SIZE);//讀出字元串,並將其儲存在char s[]中

printf(“%s”,s);//列印字元串

}

return 0;

}

三.進程間通信——IPC

①信號量通信

sem.c

#include unistd.h

#include stdlib.h

#include stdio.h

#include sys/types.h

#include sys/ipc.h

#include sys/sem.h

/*聯合體變數*/

union semun

{

int val; //信號量初始值

struct semid_ds *buf;

unsigned short int *array;

struct seminfo *__buf;

};

/*函數聲明,信號量定義*/

static int set_semvalue(void); //設置信號量

static void del_semvalue(void);//刪除信號量

static int semaphore_p(void); //執行P操作

static int semaphore_v(void); //執行V操作

static int sem_id; //信號量標識符

int main(int argc, char *argv[])

{

int i;

int pause_time;

char op_char = ‘O’;

srand((unsigned int)getpid());

sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);//創建一個信號量,IPC_CREAT表示創建一個新的信號量

/*如果有參數,設置信號量,修改字元*/

if (argc 1)

{

if (!set_semvalue())

{

fprintf(stderr, “Failed to initialize semaphore/n”);

exit(EXIT_FAILURE);

}

op_char = ‘X’;

sleep(5);

}

for(i = 0; i 10; i++)

{

/*執行P操作*/

if (!semaphore_p())

exit(EXIT_FAILURE);

printf(“%c”, op_char);

fflush(stdout);

pause_time = rand() % 3;

sleep(pause_time);

printf(“%c”, op_char);

fflush(stdout);

/*執行V操作*/

if (!semaphore_v())

exit(EXIT_FAILURE);

pause_time = rand() % 2;

sleep(pause_time);

}

printf(“/n%d – finished/n”, getpid());

if (argc 1)

{

sleep(10);

del_semvalue(); //刪除信號量

}

exit(EXIT_SUCCESS);

}

/*設置信號量*/

static int set_semvalue(void)

{

union semun sem_union;

sem_union.val = 1;

if (semctl(sem_id, 0, SETVAL, sem_union) == -1)

return(0);

return(1);

}

/*刪除信號量*/

static void del_semvalue(void)

{

union semun sem_union;

if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1)

fprintf(stderr, “Failed to delete semaphore/n”);

}

/*執行P操作*/

static int semaphore_p(void)

{

struct sembuf sem_b;

sem_b.sem_num = 0;

sem_b.sem_op = -1; /* P() */

sem_b.sem_flg = SEM_UNDO;

if (semop(sem_id, sem_b, 1) == -1)

{

fprintf(stderr, “semaphore_p failed/n”);

return(0);

}

return(1);

}

/*執行V操作*/

static int semaphore_v(void)

{

struct sembuf sem_b;

sem_b.sem_num = 0;

sem_b.sem_op = 1; /* V() */

sem_b.sem_flg = SEM_UNDO;

if (semop(sem_id, sem_b, 1) == -1)

{

fprintf(stderr, “semaphore_v failed/n”);

return(0);

}

return(1);

}

②消息隊列通信

send.c

#include stdlib.h

#include stdio.h

#include string.h

#include errno.h

#include unistd.h

#include sys/types.h

#include sys/ipc.h

#include sys/msg.h

#define MAX_TEXT 512

/*用於消息收發的結構體–my_msg_type:消息類型,some_text:消息正文*/

struct my_msg_st

{

long int my_msg_type;

char some_text[MAX_TEXT];

};

int main()

{

int running = 1;//程序運行標識符

struct my_msg_st some_data;

int msgid;//消息隊列標識符

char buffer[BUFSIZ];

/*創建與接受者相同的消息隊列*/

msgid = msgget((key_t)1234, 0666 | IPC_CREAT);

if (msgid == -1)

{

fprintf(stderr, “msgget failed with error: %d/n”, errno);

exit(EXIT_FAILURE);

}

/*向消息隊列中發送消息*/

while(running)

{

printf(“Enter some text: “);

fgets(buffer, BUFSIZ, stdin);

some_data.my_msg_type = 1;

strcpy(some_data.some_text, buffer);

if (msgsnd(msgid, (void *)some_data, MAX_TEXT, 0) == -1)

{

fprintf(stderr, “msgsnd failed/n”);

exit(EXIT_FAILURE);

}

if (strncmp(buffer, “end”, 3) == 0)

{

running = 0;

}

}

exit(EXIT_SUCCESS);

}

receive.c

#include stdlib.h

#include stdio.h

#include string.h

#include errno.h

#include unistd.h

#include sys/types.h

#include sys/ipc.h

#include sys/msg.h

/*用於消息收發的結構體–my_msg_type:消息類型,some_text:消息正文*/

struct my_msg_st

{

long int my_msg_type;

char some_text[BUFSIZ];

};

int main()

{

int running = 1;//程序運行標識符

int msgid; //消息隊列標識符

struct my_msg_st some_data;

long int msg_to_receive = 0;//接收消息的類型–0表示msgid隊列上的第一個消息

/*創建消息隊列*/

msgid = msgget((key_t)1234, 0666 | IPC_CREAT);

if (msgid == -1)

{

fprintf(stderr, “msgget failed with error: %d/n”, errno);

exit(EXIT_FAILURE);

}

/*接收消息*/

while(running)

{

if (msgrcv(msgid, (void *)some_data, BUFSIZ,msg_to_receive, 0) == -1)

{

fprintf(stderr, “msgrcv failed with error: %d/n”, errno);

exit(EXIT_FAILURE);

}

printf(“You wrote: %s”, some_data.some_text);

if (strncmp(some_data.some_text, “end”, 3) == 0)

{

running = 0;

}

}

/*刪除消息隊列*/

if (msgctl(msgid, IPC_RMID, 0) == -1)

{

fprintf(stderr, “msgctl(IPC_RMID) failed/n”);

exit(EXIT_FAILURE);

}

exit(EXIT_SUCCESS);

}

③共享內存通信

share.h

#define TEXT_SZ 2048 //申請共享內存大小

struct shared_use_st

{

int written_by_you; //written_by_you為1時表示有數據寫入,為0時表示數據已經被消費者提走

char some_text[TEXT_SZ];

};

producer.c

#include unistd.h

#include stdlib.h

#include stdio.h

#include string.h

#include sys/types.h

#include sys/ipc.h

#include sys/shm.h

#include “share.h”

int main()

{

int running = 1; //程序運行標誌位

void *shared_memory = (void *)0;

struct shared_use_st *shared_stuff;

char buffer[BUFSIZ];

int shmid; //共享內存標識符

/*創建共享內存*/

shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);

if (shmid == -1)

{

fprintf(stderr, “shmget failed/n”);

exit(EXIT_FAILURE);

}

/*將共享內存連接到一個進程的地址空間中*/

shared_memory = shmat(shmid, (void *)0, 0);//指向共享內存第一個位元組的指針

if (shared_memory == (void *)-1)

{

fprintf(stderr, “shmat failed/n”);

exit(EXIT_FAILURE);

}

printf(“Memory attached at %X/n”, (int)shared_memory);

shared_stuff = (struct shared_use_st *)shared_memory;

/*生產者寫入數據*/

while(running)

{

while(shared_stuff-written_by_you == 1)

{

sleep(1);

printf(“waiting for client…/n”);

}

printf(“Enter some text: “);

fgets(buffer, BUFSIZ, stdin);

strncpy(shared_stuff-some_text, buffer, TEXT_SZ);

shared_stuff-written_by_you = 1;

if (strncmp(buffer, “end”, 3) == 0)

{

running = 0;

}

}

/*該函數用來將共享內存從當前進程中分離,僅使得當前進程不再能使用該共享內存*/

if (shmdt(shared_memory) == -1)

{

fprintf(stderr, “shmdt failed/n”);

exit(EXIT_FAILURE);

}

printf(“producer exit./n”);

exit(EXIT_SUCCESS);

}

customer.c

#include unistd.h

#include stdlib.h

#include stdio.h

#include string.h

#include sys/types.h

#include sys/ipc.h

#include sys/shm.h

#include “share.h”

int main()

{

int running = 1;//程序運行標誌位

void *shared_memory = (void *)0;

struct shared_use_st *shared_stuff;

int shmid; //共享內存標識符

srand((unsigned int)getpid());

/*創建共享內存*/

shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);

if (shmid == -1)

{

fprintf(stderr, “shmget failed/n”);

exit(EXIT_FAILURE);

}

/*將共享內存連接到一個進程的地址空間中*/

shared_memory = shmat(shmid, (void *)0, 0);//指向共享內存第一個位元組的指針

if (shared_memory == (void *)-1)

{

fprintf(stderr, “shmat failed/n”);

exit(EXIT_FAILURE);

}

printf(“Memory attached at %X/n”, (int)shared_memory);

shared_stuff = (struct shared_use_st *)shared_memory;

shared_stuff-written_by_you = 0;

/*消費者讀取數據*/

while(running)

{

if (shared_stuff-written_by_you)

{

printf(“You wrote: %s”, shared_stuff-some_text);

sleep( rand() % 4 );

shared_stuff-written_by_you = 0;

if (strncmp(shared_stuff-some_text, “end”, 3) == 0)

{

running = 0;

}

}

}

/*該函數用來將共享內存從當前進程中分離,僅使得當前進程不再能使用該共享內存*/

if (shmdt(shared_memory) == -1)

{

fprintf(stderr, “shmdt failed/n”);

exit(EXIT_FAILURE);

}

/*將共享內存刪除,所有進程均不能再訪問該共享內存*/

if (shmctl(shmid, IPC_RMID, 0) == -1)

{

fprintf(stderr, “shmctl(IPC_RMID) failed/n”);

exit(EXIT_FAILURE);

}

exit(EXIT_SUCCESS);

}

摘自:

C語言如何實現多線程同時運行

1、點擊菜單欄的「Project」選項卡,下拉列表的最後一項「Project options…」是對當前工程的的屬性進行設置的。

2、選擇彈出對話框中的「Compiler」選項卡。

3、將其中的「Runtime Library」的選擇改為「Multithreaded (LIB)」。

4、將看到對話框最下面的文本框中發生了一些變化,新增了「-MT」選項,這與編譯器一開始所報的錯誤提示給出的解決方案一致。

5、頁面的設置完成後,再對該源碼進行編譯時,就能愉快地看到編譯完全成功。

原創文章,作者:QRRK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/132784.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
QRRK的頭像QRRK
上一篇 2024-10-03 23:54
下一篇 2024-10-03 23:54

相關推薦

  • AES加密解密演算法的C語言實現

    AES(Advanced Encryption Standard)是一種對稱加密演算法,可用於對數據進行加密和解密。在本篇文章中,我們將介紹C語言中如何實現AES演算法,並對實現過程進…

    編程 2025-04-29
  • 學習Python對學習C語言有幫助嗎?

    Python和C語言是兩種非常受歡迎的編程語言,在程序開發中都扮演著非常重要的角色。那麼,學習Python對學習C語言有幫助嗎?答案是肯定的。在本文中,我們將從多個角度探討Pyth…

    編程 2025-04-29
  • Python被稱為膠水語言

    Python作為一種跨平台的解釋性高級語言,最大的特點是被稱為”膠水語言”。 一、簡單易學 Python的語法簡單易學,更加人性化,這使得它成為了初學者的入…

    編程 2025-04-29
  • OpenJudge答案1.6的C語言實現

    本文將從多個方面詳細闡述OpenJudge答案1.6在C語言中的實現方法,幫助初學者更好地學習和理解。 一、需求概述 OpenJudge答案1.6的要求是,輸入兩個整數a和b,輸出…

    編程 2025-04-29
  • Python按位運算符和C語言

    本文將從多個方面詳細闡述Python按位運算符和C語言的相關內容,並給出相應的代碼示例。 一、概述 Python是一種動態的、面向對象的編程語言,其按位運算符是用於按位操作的運算符…

    編程 2025-04-29
  • Python線程等待指南

    本文將從多個方面詳細講解Python線程等待的相關知識。 一、等待線程結束 在多線程編程中,經常需要等待線程執行完畢再進行下一步操作。可以使用join()方法實現等待線程執行完畢再…

    編程 2025-04-29
  • Python語言由荷蘭人為中心的全能編程開發工程師

    Python語言是一種高級語言,很多編程開發工程師都喜歡使用Python語言進行開發。Python語言的創始人是荷蘭人Guido van Rossum,他在1989年聖誕節期間開始…

    編程 2025-04-28
  • Python語言設計基礎第2版PDF

    Python語言設計基礎第2版PDF是一本介紹Python編程語言的經典教材。本篇文章將從多個方面對該教材進行詳細的闡述和介紹。 一、基礎知識 本教材中介紹了Python編程語言的…

    編程 2025-04-28
  • Python兩個線程交替列印1到100

    這篇文章的主題是關於Python多線程的應用。我們將會通過實際的代碼,學習如何使用Python兩個線程交替列印1到100。 一、創建線程 在Python中,我們可以使用Thread…

    編程 2025-04-28
  • Python語言實現人名最多數統計

    本文將從幾個方面詳細介紹Python語言實現人名最多數統計的方法和應用。 一、Python實現人名最多數統計的基礎 1、首先,我們需要了解Python語言的一些基礎知識,如列表、字…

    編程 2025-04-28

發表回復

登錄後才能評論