當前位置:首頁 » 操作系統 » c多線程源碼

c多線程源碼

發布時間: 2022-08-03 19:05:32

c語言實現多線程

目錄:

  1. linux操作系統,C語言實現多線程

  2. Windows操作系統,C語言實現多線程

  3. Windows下的多線程(不帶停止)

Linux操作系統,C語言實現多線程:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void*ThreadOne(void*threadArg)
{
printf("線程開始啦,參數是:%s ",(char*)threadArg);
returnNULL;
}
intmain(void)
{
pthread_tThreadID;/*記錄線程標識符*/
void*waitingResult;/*等待線程退出的等待結果*/
interrorCode;/*記錄線程的錯誤代碼*/
char*aMessage="這是線程的參數";
/*創建並啟動線程ThreadOne。若返回值非零,則線程創建失敗*/
errorCode=pthread_create(&ThreadID,NULL,ThreadOne,aMessage);
if(errorCode!=0)
{
printf("線程ThreadOne創建失敗。錯誤代碼:%d ",errorCode);
returnEXIT_FAILURE;
}
/*等待線程標識符為的ThreadID的線程結束*/
errorCode=pthread_join(ThreadID,&waitingResult);
if(errorCode!=0)
{
printf("等待線程退出等待失敗。錯誤代碼:%d ",errorCode);
returnEXIT_FAILURE;
}
printf("線程的返回值是%p ",waitingResult);
returnEXIT_SUCCESS;
}

Windows操作系統,C語言實現多線程:

#include<stdio.h>
#include<windows.h>
DWORDAPIENTRYThreadOne(LPVOIDthreadArg)
{
printf("線程開始啦,參數是:%s ",(char*)threadArg);
return0;
}
intmain(void)
{
HANDLEhThread;/*記錄線程句柄*/
DWORDThreadID;/*記錄線程ID號*/
DWORDwaitingResult;/*等待線程退出的等待結果*/
DWORDthreadExitCode;/*記錄線程的返回值*/
char*aMessage="這是線程的參數";
/*創建並啟動線程ThreadOne,返回值為線程句柄,賦值給hThread*/
hThread=CreateThread(NULL,0L,ThreadOne,(LPVOID)aMessage,0L,&ThreadID);
if(hThread==NULL)
{
printf("線程ThreadOne創建失敗。錯誤代碼:%lu ",GetLastError());
returnEXIT_FAILURE;
}
/*等待線程句柄為的hThread線程結束*/
waitingResult=WaitForSingleObject(hThread,INFINITE);
if(waitingResult==WAIT_FAILED)
{
printf("等待線程退出等待失敗。錯誤代碼:%lu ",GetLastError());
returnEXIT_FAILURE;
}
if(GetExitCodeThread(hThread,&threadExitCode))
printf("線程的返回值是%lu ",threadExitCode);
else
printf("獲取線程的返回值獲取失敗。錯誤代碼:%lu ",GetLastError());
returnEXIT_SUCCESS;
}

Windows下的多線程:(不帶停止)

#include<stdio.h>
#include<windows.h>
DWORDWINAPIoxianchen(LPVOIDlpParam);
intmain(intargc,char*argv[])
{
intnum=0;
CreateThread(NULL,NULL,oxianchen,&num,NULL,NULL);
while(1)
{
num++;
printf("主線程!%05d ",nu***eep(40);
}
return0;
}
DWORDWINAPIoxianchen(LPVOIDlpParam)
{
int*a=lpParam;
while(1)
{
++*a;
printf("副線程!%05d0x%p ",*a,a);
Sleep(80);
}
return0;
}

⑵ 如何利用多線程,實現處理圖像的同時,實時感應滑鼠的移動,求c語言源代碼!


你這個問題可是超過200分的啊,
這個往大了說是一個比較復雜的設計方案。

實際上C語言是沒有多線程的概念的,但是我們可以通過Task來實現多任務。

簡單的說,可以採取以下方案:
定義一個主Task,將其置為常駐Task,用以進行Task調度和Task的啟動/終了和交互的管理。
定義一個Task優先順序列表,用優先順序來作為Task調度和管理的基礎。
定義一個共享域,和相應的事件分發/廣播/傳遞的管理機制,由主Task來實現各Task間的事件傳遞。
定義3個List,實現Active,Ready,Dead的Task的管理和調度。
定義各普通Task,包含Task基本信息:Task的棧指針,Task情報,Task存儲空間大小,Task的優先順序,Task的事件列表(定義可以接收/發送的事件,以及可以排隊的事件的個數),以及如果需要的話可以定義Task的從屬(父子)關系。

另外還有幾個注意點:
1. 通過C的臨界域(critical section)結合PV操作來實現某些Task的原子性處理要求。
2. 通過Signal來實現中斷和再開
3. 如果需要處理中斷和再開的話,一定要注意現場保護
4. 同優先順序的Task可以通過時間片輪循的方式進行多任務實現

暫時就想到這么多,有不明白的通過消息進一步交流吧:)

⑶ C語言多線程如何實現

線程之間沒有共享數據,不需要線程同步
你在主函數裡面,把線程銷毀的太快了,線程都沒來得及執行完你就退出了,在創建完線程之後,加個sleep等待幾秒再銷毀線程。
同時注意一下,主進程退出的話,所有線程也會退出。

如果要准確的等待線程執行完再銷毀,可以使用join方法或者共享標志位的方法

⑷ 急求!!多線程生產者消費者問題的c語言程序,要源碼、已在linux中執行過的文件,最好有截圖!!

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/time.h>
#include<string.h>

#define BUFSIZE 4096

#define SEM_IN_TASK "INX_TASK"
#define SEM_OUT_TASK "OUTX_TASK"

sem_t *sem_in;
sem_t *sem_out;

main(int argc, char** argv) // map a normal file as shared mem:
{
int fd,i;
char *p_map;
char temp;

fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777);
//lseek(fd,sizeof(people)*5-1,SEEK_SET);
write(fd,"",1);

p_map = (char*) mmap( NULL,BUFSIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0 );//建立共享內存
close( fd );

sem_unlink(SEM_IN_TASK);
sem_unlink(SEM_OUT_TASK);

sem_in = sem_open(SEM_IN_TASK,O_CREAT|O_EXCL,0644,1); //1ok
sem_out=sem_open(SEM_OUT_TASK,O_CREAT|O_EXCL,0644,0); //0ok
printf("[sem_in] [%d]\n",sem_in);
printf("[sem_out] [%d]\n",sem_out);

if(sem_in == SEM_FAILED||sem_out == SEM_FAILED)
{
perror("wangsha-unable to create semaphore");
sem_unlink(SEM_IN_TASK);
sem_unlink(SEM_OUT_TASK);
exit(-1);
}

memset(p_map,0,BUFSIZE);

while(1)
{
//printf("---------A waitting B-----------\n\n\n\n");
sem_wait(sem_out);

printf("A:%s\n",p_map );

memset(p_map,'a',100);

sem_post(sem_in);

//printf("------------A emit B-----------\n\n\n\n");
}
munmap( p_map, BUFSIZE );
printf( "umap ok \n" );
}

#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/time.h>
#include<string.h>

#define SEM_IN_TASK "INX_TASK"
#define SEM_OUT_TASK "OUTX_TASK"

#define BUFSIZE 4096

sem_t *sem_in;
sem_t *sem_out;

main(int argc, char** argv) // map a normal file as shared mem:
{
int fd =-1;
int i= 0;
char *p_map;
double consumetime = 0.0;
struct timeval process_stat , process_end;

fd=open( argv[1],O_CREAT|O_RDWR,00777 );
p_map = (char*)mmap(NULL,BUFSIZE,PROT_READ|PROT_WRITE, MAP_SHARED,fd,0);

sem_in = sem_open(SEM_IN_TASK,O_CREAT,0644,0); //0ok
sem_out=sem_open(SEM_OUT_TASK,O_CREAT,0644,1); //1ok
printf("[sem_in] [%d]\n",sem_in);
printf("[sem_out] [%d]\n",sem_out);

if(sem_in == SEM_FAILED||sem_out == SEM_FAILED)
{
perror("unable to create semaphore-wang");
sem_unlink(SEM_OUT_TASK);
sem_unlink(SEM_IN_TASK);
exit(-1);
}
memset(p_map,0,BUFSIZE);
//gettimeofday(&process_stat,NULL);
//while(1)
for(i =0;i<50000;i++)
{
memset(p_map,'b',100);
//printf("------------B emit A-----------\n\n\n\n");
sem_post(sem_out);
usleep(200);
sem_wait(sem_in);
//printf("------------A emit B-----------\n\n\n\n");
printf( "B:%s\n",p_map );
}
//gettimeofday(&process_end,NULL);
//consumetime = (double)(process_end.tv_sec - process_stat.tv_sec)*1e6 +(double)(process_end.tv_usec - process_stat.tv_usec)/1e6;
//printf("consumetime:[%f]\n",consumetime);

munmap( p_map,BUFSIZE );
}
如果對你有幫助,請給分哦,謝謝!

⑸ c語言中怎樣創建多線程。最好有一個例子,謝謝!!

/*這是我寫的最簡單的多線程程序,看懂不?*/
#include <windows.h>
#include <stdio.h>
//#include <strsafe.h>

DWORD WINAPI ThreadProc1( LPVOID lpParam )
{

int i=0,j=0;
while(1)
{
printf("hello,this thread 1 ...\n");

//延時
for(i=0;i<200000000;i++)
{
;
}
}
}

DWORD WINAPI ThreadProc2( LPVOID lpParam )
{

int i=0,j=0;
while(1)
{
printf("hello,this thread 2 ...\n");

//延時
for(i=0;i<200000000;i++)
{
;
}
}
}

void main()
{
int i=0;
//創建線程1
CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadProc1, // thread function
NULL, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier

//創建線程2
CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadProc2, // thread function
NULL, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier

//讓主線程進入循環,主線程若退出,子線程1,2會被系統「殺死」
while(1)
{
printf("hello,this thread 0 ...\n");

//延時
for(i=0;i<200000000;i++)
{;}

}
}

⑹ C語言怎樣實現多線程

首先你要有控制蛇移動方向的全局變數(定義在main以外因為線程函數也要調用它,每次鍵盤輸入都會修改它的值), 比如 char direction 'a' ==左 'w' == 右 'd'==上 's' == 下,然後你在移動時應該是在while裡面操作的吧,你每移動一步前都讀一下direction這個變數的數值然後再控制移動方向(注意s這個鍵可以忽略因為不會倒著走) 然後你可以用pthread.h這個庫 例子是 pthread t;// 定義一個線程 pthread_create(&t, null, listen_keyboard_input, null);//建立線程執行listen_keyboard_input這個函數 這個線程執行的函數 void listen_keyboard_input(){ while(應該通過某個信號來退出這個循環,從而表示游戲結束){ direction =getchar(); } } 但是這里存在同步問題, 比如當這個線程的getchar()在給direction輔助的同時,你控制貪吃蛇移動的線程正在調用 direction的值來判斷下一個移動方向,這就會出問題,所以要加一個鎖,叫 mutex lock;這個也定義成全局變數可以使各線程共享。 pthread_mutex_t mutex; //定義一個鎖 pthread_mutex_init(&mutex, null, null);//初始化 然後把函數修改成 void listen_keyboard_input(){ while(應該通過某個信號來退出這個循環,從而表示游戲結束){ pthread_mutex_lock(&mutex); direction =getchar(); pthread_mutex_unlock(&mutex); } } 另外一個控制貪吃蛇移動的時候也要加鎖 while(.....){ char c; pthread_mutex_lock(&mutex); c = direction; pthread_mutex_unlock(&mutex); switch(c){ ................ } ................................... } 這樣就好了 注意你的控制貪吃蛇移動的部分也必須要放在另外一個pthread 裡面執行,如果放在主線程, 主線程會一直等listen_keyboard_input而什麼事都不會做 你把這兩個線程用 pthread_create 創建完成後 用 t1.join(); t2.join(); 就可以使這兩個線程並發執行了 如果你用的是linux 來編譯的,你再輸入gcc 指令後加上 -lpthread 就可以了 還有什麼不懂的你可以多找找 pthread 類的例子

⑺ c語言如何編寫一個簡單的多線程程序

這是一個多線程例子,裡面只有兩個線程,是生產者/消費者模式,已編譯通過,注釋很詳細,
如下:

/* 以生產者和消費者模型問題來闡述Linux線程的控制和通信你
生產者線程將生產的產品送入緩沖區,消費者線程則從中取出產品。
緩沖區有N個,是一個環形的緩沖池。
*/
#include <stdio.h>
#include <pthread.h>

#define BUFFER_SIZE 16

struct prodcons
{
int buffer[BUFFER_SIZE];/*實際存放數據的數組*/
pthread_mutex_t lock;/*互斥體lock,用於對緩沖區的互斥操作*/
int readpos,writepos; /*讀寫指針*/
pthread_cond_t notempty;/*緩沖區非空的條件變數*/
pthread_cond_t notfull;/*緩沖區未滿 的條件變數*/
};

/*初始化緩沖區*/
void pthread_init( struct prodcons *p)
{
pthread_mutex_init(&p->lock,NULL);
pthread_cond_init(&p->notempty,NULL);
pthread_cond_init(&p->notfull,NULL);
p->readpos = 0;
p->writepos = 0;
}

/*將產品放入緩沖區,這里是存入一個整數*/
void put(struct prodcons *p,int data)
{
pthread_mutex_lock(&p->lock);
/*等待緩沖區未滿*/
if((p->writepos +1)%BUFFER_SIZE ==p->readpos)
{
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buffer[p->writepos] =data;
p->writepos++;
if(p->writepos >= BUFFER_SIZE)
p->writepos = 0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
/*從緩沖區取出整數*/
int get(struct prodcons *p)
{
int data;
pthread_mutex_lock(&p->lock);
/*等待緩沖區非空*/
if(p->writepos == p->readpos)
{
pthread_cond_wait(&p->notempty ,&p->lock);//非空就設置條件變數notempty
}
/*讀書據,移動讀指針*/
data = p->buffer[p->readpos];
p->readpos++;
if(p->readpos == BUFFER_SIZE)
p->readpos = 0;
/*設置緩沖區未滿的條件變數*/
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
/*測試:生產站線程將1 到1000的整數送入緩沖區,消費者線程從緩沖區中獲取整數,兩者都列印信息*/
#define OVER (-1)
struct prodcons buffer;
void *procer(void *data)
{
int n;
for( n=0;n<1000;n++)
{
printf("%d ------>\n",n);
put(&buffer,n);
}
put(&buffer,OVER);
return NULL;
}
void *consumer(void *data)
{
int d;
while(1)
{
d = get(&buffer);
if(d == OVER)
break;
else
printf("----->%d\n",d);
}
return NULL;
}
int main()
{
pthread_t th_p,th_c;
void *retval;
pthread_init(&buffer);
pthread_create(&th_p,NULL,procer,0);
pthread_create(&th_c,NULL,consumer,0);
/*等待兩個線程結束*/
pthread_join(th_p, &retval);
pthread_join(th_c,&retval);
return 0;
}

⑻ C語言多線程實現

多線程隨機選號程序
以下程序運行後看起來比較有意思,像一個隨機選號程序,但不是完全按照問題所說的寫的 可供參考,要改很容易

//多線程隨機選號程序示例
#include <stdio.h>
#include <Windows.h>
#include <ctime>
#include <cstdlib>
#include <process.h>
bool g_run = true; //是否運行

void userInput(void*) //監視輸入的線程函數
{
while (true)
{
if (getchar()=='\n') //是否輸入回車
{
g_run = !g_run; //回車運行 回車暫停
}
Sleep(10); //延遲
}
}

int main()
{
srand(time(0)); //隨機數種子
_beginthread(userInput,0,NULL); //開線程
while (true)
{
if (g_run)
{
system("cls"); //清屏
int t = rand() % 1000+ 1;//1-1000的隨機數
printf("\n %d",t); //輸出
}
Sleep(50); //延遲50毫秒
}
return 0;
}

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

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

⑽ 編寫一個多線程的C程序 分割數據並分發給每個線程

不如貼英文原版要求,中文翻譯出來的要求看著不是很明白

熱點內容
電腦改群暉伺服器 發布:2024-05-06 07:57:19 瀏覽:38
冒險島忘記伺服器了怎麼查 發布:2024-05-06 07:53:42 瀏覽:240
茶葉資料庫 發布:2024-05-06 07:52:16 瀏覽:311
伺服器web訪問埠怎麼查看 發布:2024-05-06 07:35:28 瀏覽:226
蘋果id改密碼要什麼條件 發布:2024-05-06 07:34:47 瀏覽:805
鎮江節點伺服器測試ip 發布:2024-05-06 07:15:05 瀏覽:540
sqlserver表格 發布:2024-05-06 07:09:54 瀏覽:612
雪鐵龍凡爾賽選哪個配置 發布:2024-05-06 06:56:04 瀏覽:571
福睿斯配置怎麼樣 發布:2024-05-06 06:50:16 瀏覽:103
微生物資料庫 發布:2024-05-06 06:47:33 瀏覽:605