中易网

C语言如何实现多线程同时运行

答案:3  悬赏:20  
解决时间 2021-01-11 18:28
  • 提问者网友:伴风望海
  • 2021-01-11 14:27
C语言如何实现多线程同时运行
最佳答案
  • 二级知识专家网友:千夜
  • 2021-01-11 15:16
1、使用pthread库执行多线程,这个是Linux下的线程库 Windows下应该有自己的API,不过这种东西一般还是以Linux为标准。pthread_create()创建一个线程,传入fun()的函数指针就行了。



2、例程:
#include 
#include 
#include 
#include 
#define MAX 10
pthread_t thread[2];
pthread_mutex_t mut;
int number=0, i;
void *thread1()
{
printf ("thread1 : I'm thread 1
");
for (i = 0; i < MAX; i++)
{
printf("thread1 : number = %d
",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1 :主函数在等我完成任务吗?
");
pthread_exit(NULL);
}
void *thread2()
{
printf("thread2 : I'm thread 2
");
for (i = 0; i < MAX; i++)
{
printf("thread2 : number = %d
",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2 :主函数在等我完成任务吗?
");
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread)); //comment1

if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2
printf("线程1创建失败!
");
else
printf("线程1被创建
");
if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3
printf("线程2创建失败");
else
printf("线程2被创建
");
}
void thread_wait(void)
{

if(thread[0] !=0) { //comment4
pthread_join(thread[0],NULL);
printf("线程1已经结束
");
}
if(thread[1] !=0) { //comment5
pthread_join(thread[1],NULL);
printf("线程2已经结束
");
}
}
int main()
{

pthread_mutex_init(&mut,NULL);
printf("我是主函数哦,我正在创建线程,呵呵
");
thread_create();
printf("我是主函数哦,我正在等待线程完成任务阿,呵呵
");
thread_wait();
return 0;
}
全部回答
  • 1楼网友:傲气稳了全场
  • 2021-01-11 16:24
c11自带多线程库<threads.h>,旧版本的c则要调用对应的系统api或第三方库
  • 2楼网友:末日狂欢
  • 2021-01-11 15:30
使用pthread库执行多线程,这个是Linux下的线程库 Windows下应该有自己的API,不过这种东西一般还是以Linux为标准。pthread_create()创建一个线程,传入fun()的函数指针就行了。
然后这个Beep()的需求要进行线程间通信,可以用共享内存的方法,设一个bool变量flag共享,然后beep的时候设为false,beep完设成true。fun()里面每次看一下这个flag,是false的话就不做动作等下一秒,基本可以满足需求。
这样做的好处是实现简单,但时间是以1s为单位的。如果要8秒结束立刻执行,需要用条件变量的方法来控制,比较复杂,这样的实现方式一个可以满足需求了。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息