linux下的C\C++多進(jìn)程多線程編程實例詳解
linux下的C\C++多進(jìn)程多線程編程實例詳解
1、多進(jìn)程編程
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t child_pid;
/* 創(chuàng)建一個子進(jìn)程 */
child_pid = fork();
if(child_pid == 0)
{
printf("child pid\n");
exit(0);
}
else
{
printf("father pid\n");
sleep(60);
}
return 0;
}
2、多線程編程
#include <stdio.h>
#include <pthread.h>
struct char_print_params
{
char character;
int count;
};
void *char_print(void *parameters)
{
struct char_print_params *p = (struct char_print_params *)parameters;
int i;
for(i = 0; i < p->count; i++)
{
fputc(p->character,stderr);
}
return NULL;
}
int main()
{
pthread_t thread1_id;
pthread_t thread2_id;
struct char_print_params thread1_args;
struct char_print_params thread2_args;
thread1_args.character = 'x';
thread1_args.count = 3000;
pthread_create(&thread1_id, NULL, &char_print, &thread1_args);
thread2_args.character = 'o';
thread2_args.count = 2000;
pthread_create(&thread2_id, NULL, &char_print, &thread2_args);
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
return 0;
}
3、線程同步與互斥
1)、互斥
pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL); /*也可以用下面的方式初始化*/ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); /* 互斥 */ thread_flag = value; pthread_mutex_unlock(&mutex);
2)、條件變量
int thread_flag = 0;
pthread_mutex_t mutex;
pthread_cond_t thread_flag_cv;\
void init_flag()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&thread_flag_cv, NULL);
thread_flag = 0;
}
void *thread_function(void *thread_flag)
{
while(1)
{
pthread_mutex_lock(&mutex);
while(thread_flag != 0 )
{
pthread_cond_wait(&thread_flag_cv, &mutex);
}
pthread_mutex_unlock(&mutex);
do_work();
}
return NULL;
}
void set_thread_flag(int flag_value)
{
pthread_mutex_lock(&mutex);
thread_flag = flag_value;
pthread_cond_signal(&thread_flag_cv);
pthread_mutex_unlock(&mutex);
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
centos7 無線網(wǎng)卡驅(qū)動的安裝及無線網(wǎng)絡(luò)的配置詳解
本篇文章主要介紹了centos7 無線網(wǎng)卡驅(qū)動的安裝及無線網(wǎng)絡(luò)的配置詳解,具有一定的參考價值,有興趣的可以了解一下。2017-03-03
linux環(huán)境搭建圖數(shù)據(jù)庫neo4j的講解
今天小編就為大家分享一篇關(guān)于linux環(huán)境搭建圖數(shù)據(jù)庫neo4j的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04
詳解Linux文件中的數(shù)據(jù)是如何被寫進(jìn)磁盤
Linux 中,我們的每一個進(jìn)程,打開的每一個文件都要有自己的 struct inode 對象和自己的文件頁緩沖區(qū)(就是所謂的內(nèi)核緩沖區(qū)),本文我們給大家介紹了Linux文件中的數(shù)據(jù)是如何被寫進(jìn)磁盤,需要的朋友可以參考下2024-05-05
Linux系統(tǒng)中KafKa安裝和使用方法 java客戶端連接kafka過程
這篇文章主要介紹了Linux系統(tǒng)中KafKa安裝和使用方法 java客戶端連接kafka過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Linux 實現(xiàn)定時文件占用磁盤空間大小操作方法
這篇文章主要介紹了Linux 實現(xiàn)定時文件占用磁盤空間大小操作方法,本文內(nèi)容簡短非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
詳解CentOS7安裝配置Apache HTTP Server
本篇文章主要介紹了CentOS7安裝配置Apache HTTP Server,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
動態(tài)在線擴(kuò)容root根分區(qū)大小的方法詳解
這篇文章主要給大家介紹了關(guān)于如何動態(tài)在線擴(kuò)容root根分區(qū)大小的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05

