当前位置:首页 » 编程软件 » c多线程编程实例

c多线程编程实例

发布时间: 2022-09-20 11:06:15

‘壹’ 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语言怎样实现多线程

首先你要有控制蛇移动方向的全局变量(定义在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);

}

热点内容
微信qq音乐缓存 发布:2025-05-14 16:16:16 浏览:468
c语言回收内存 发布:2025-05-14 16:16:08 浏览:143
2021国产安卓顶级旗舰买哪个 发布:2025-05-14 16:15:36 浏览:300
linux自学视频 发布:2025-05-14 16:14:49 浏览:255
我的世界服务器崩了重启 发布:2025-05-14 16:09:37 浏览:44
android深拷贝 发布:2025-05-14 16:09:35 浏览:153
cf电脑版转服务器神器还在吗 发布:2025-05-14 16:09:02 浏览:211
百度文库服务器如何搭建 发布:2025-05-14 16:09:00 浏览:248
安卓微信删除的好友怎么找回 发布:2025-05-14 16:08:56 浏览:706
iphone的访问限制密码忘记了怎么办 发布:2025-05-14 16:08:56 浏览:184