c多線程編程實例
『壹』 c語言實現多線程
目錄:
linux操作系統,C語言實現多線程
Windows操作系統,C語言實現多線程
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語言怎樣實現多線程
首先你要有控制蛇移動方向的全局變數(定義在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語言多線程實現
你是想模擬多線程?還是想用WIN SDK寫多線程?
要是是WINSDK 里的東西 看看孫鑫的 MFC 視頻就會有的,在第15章,是用WINSDK編寫的。
『肆』 編寫一個多線程程序(C++),急呀,各位請幫忙。簡單的就好了。
#pragma once
#include <Windows.h>
HANDLE threadHandle;
DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
//該線程做的事情為:求iA+iB的和(如果你有什麼代碼要你創建的線程運行的話,就將代碼添加在這里)
int iA,iB;
iA = 5;
iB = 6;
int iSum = iA+iB;
//終止線程
TerminateThread( threadHandle, 0 );
return 0;
}
int main()
{
//創建線程(創建線程後,線程函數會自動調用)
threadHandle = CreateThread( NULL, //一般為NULL
0, //一般為0
ThreadProc, //線程函數(自動調用)
NULL, //一般為NULL
0, //一般為0
NULL //
);
system( "pause" );
}
『伍』 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語言在windows或者Linux上面,編寫一個多線程程序
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
int *pt=(int*)lpParam;
printf("I am tread %d\r\n",*pt);
}
int main()
{
const int Count=4;
int datas[Count];
DWORD dwThreadId[Count];
HANDLE hThread[Count];
int i;
for(i=0;i<Count;i++)
{
datas[i]=i+1;
hThread[i]=CreateThread(NULL,0,ThreadProc,&datas[i],0,&dwThreadId[i]);
}
WaitForMultipleObjects(Count,hThread,TRUE,INFINITE);
for(i=0;i<Count;i++)
{
CloseHandle(hThread[i]);
}
system("PAUSE");
return EXIT_SUCCESS;
}
『柒』 求c#多線程實例
Thread th=new Thread(new ThreadStart(方法));
th.Name="aa" 為線程命名
th.Priority=ThreadPriority.Highest 最高 //運行的優先順序
.Normal 預設
.Lowest 最底
th.Start();
lock(對象)
{
//代碼 保證一個線程執行完這段代碼之後另外 //一個線才執行這段代碼,線程有序
}
Start();
Sleep(毫秒數); //休眠,這個毫秒等待完成後自動繼續執行
Suspend(); //掛起,不自動恢復
Resume(); //通過Resume去恢復一個掛起的線程
Abort(); //停止當前線程
示例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading; //命名空間
namespace WindowsApplication19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread th1;
Thread th2;
Thread th3;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//關閉線程
th1.Abort();
th2.Abort();
th3.Abort();
}
private void button1_Click(object sender, EventArgs e)
{
th1 = new Thread(new ThreadStart(Run1)); //固定寫法
th2 = new Thread(new ThreadStart(Run2));
th3 = new Thread(new ThreadStart(Run3));
th1.Priority = ThreadPriority.Highest; //設置優先順序
th2.Priority = ThreadPriority.AboveNormal;
th3.Priority = ThreadPriority.Normal;
th1.Name = "aa"; //設置名字
th2.Name = "bb";
th3.Name = "cc";
th1.Start(); //啟動線程
th2.Start();
th3.Start();
}
private void Run1()
{
for (int i = 0; i < 100; i++)
{
this.progressBar1.Value = i;
Thread.Sleep(100);
}
}
private void Run2()
{
for (int i = 0; i < 100; i++)
{
this.progressBar2.Value = i;
Thread.Sleep(100);
}
}
private void Run3()
{
for (int i = 0; i < 100; i++)
{
this.progressBar3.Value = i;
Thread.Sleep(100);
}
}
}
}
『捌』 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程序 分割數據並分發給每個線程
不如貼英文原版要求,中文翻譯出來的要求看著不是很明白
『拾』 c 語言多線程編程 , 創建四個線程 , 依次往一個char str[1000]型全局 數組中 寫 字元 A,B,C,D。
#include"stdio.h"
#include"process.h"
#include"stdlib.h"
#include"windows.h"
//4個全局事件變數,用於控制寫入順序
HANDLEevent1,event2,event3,event4;
intcount=0;//計數變數
charstr[1000]={0};
//
voidthread1(LPVOIDparam)
{
while(TRUE)
{
WaitForSingleObject(event4,INFINITE);
if(count>=4)//
{
SetEvent(event1);
break;
}
str[count++]='A';
SetEvent(event1);
}
}
voidthread2(LPVOIDparam)
{
while(TRUE)
{
WaitForSingleObject(event1,INFINITE);
if(count>=4)//
{
SetEvent(event2);
break;
}
str[count++]='B';
SetEvent(event2);
}
}
voidthread3(LPVOIDparam)
{
while(TRUE)
{
WaitForSingleObject(event2,INFINITE);
if(count>=4)//
{
SetEvent(event3);
break;
}
str[count++]='C';
SetEvent(event3);
}
}
voidthread4(LPVOIDparam)
{
while(TRUE)
{
WaitForSingleObject(event3,INFINITE);
if(count>=4)//
{
SetEvent(event4);
break;
}
str[count++]='D';
SetEvent(event4);
}
_endthread();
}
//
voidmain()
{
HANDLEhthread[4];
event1=CreateEvent(NULL,FALSE,FALSE,NULL);
event2=CreateEvent(NULL,FALSE,FALSE,NULL);
event3=CreateEvent(NULL,FALSE,FALSE,NULL);
event4=CreateEvent(NULL,FALSE,FALSE,NULL);
hthread[0]=(HANDLE)_beginthread(thread1,0,NULL);
hthread[1]=(HANDLE)_beginthread(thread2,0,NULL);
hthread[2]=(HANDLE)_beginthread(thread3,0,NULL);
hthread[3]=(HANDLE)_beginthread(thread4,0,NULL);
SetEvent(event4);
WaitForMultipleObjects(4,hthread,TRUE,INFINITE);
printf("%s ",str);
}