当前位置:首页 » 操作系统 » 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-19 05:49:29 浏览:589
开启php短标签 发布:2024-05-19 05:44:12 浏览:473
android各国语言 发布:2024-05-19 05:42:54 浏览:247
微信什么资料都没怎么找回密码 发布:2024-05-19 05:35:34 浏览:907
填志愿密码是什么 发布:2024-05-19 05:30:23 浏览:318
城堡争霸自动掠夺脚本 发布:2024-05-19 05:22:06 浏览:204
asp编程工具 发布:2024-05-19 05:20:36 浏览:143
insertpython 发布:2024-05-19 05:12:26 浏览:244
androidant编译 发布:2024-05-19 05:04:11 浏览:988
按键脚本优化 发布:2024-05-19 04:59:57 浏览:752