linux线程定时打印,在linux中安排两个线程两个打印数字模式

如何使用线程和一个全局变量来完成任务?

如果您正在使用Linux,您可以使用POSIX库为C编程语言线程。图书馆是。然而,作为替代方案,在MSVC上的gcc和g++和(具有旧版本)得到很好支持的相当便携且相对非侵入性的库是openMP。

它不是标准的C和C++,但OpenMP本身就是一个标准。

如何在Linux中按期望的顺序安排线程?

要实现所需的打印操作,您需要有一个全局变量,可以通过您的两个线程访问该变量。两个线程轮流访问全局变量variable并执行操作(increment和print)。但是,要实现desired order,则需要有一个mutex。互斥量是一种互斥信号量,一次只允许一个寄存器的信号量的特殊变体。当您拥有资源实例(global variable in your case)并且该资源正由两个线程共享时,可以使用它。锁定该互斥锁后的线程可以独占访问资源实例,并且在完成操作后,线程应释放其他线程的互斥锁。

您可以从here的开始使用线程和互斥锁。

您的问题的可能的解决方案之一可能是这个程序在下面给出。但是,我建议你自己试试看,然后看看我的解决方案。

#include

#include

#include

pthread_mutex_t lock;

int variable=0;

#define ONE_TIME_INC 5

#define MAX 100

void *thread1(void *arg)

{

while (1) {

pthread_mutex_lock(&lock);

printf("Thread1: \n");

int i;

for (i=0; i

if (variable >= MAX)

goto RETURN;

printf("\t\t%d\n", ++variable);

}

printf("Thread1: Sleeping\n");

pthread_mutex_unlock(&lock);

usleep(1000);

}

RETURN:

pthread_mutex_unlock(&lock);

return NULL;

}

void *thread2(void *arg)

{

while (1) {

pthread_mutex_lock(&lock);

printf("Thread2: \n");

int i;

for (i=0; i

if (variable >= MAX)

goto RETURN;

printf("%d\n", ++variable);

}

printf("Thread2: Sleeping\n");

pthread_mutex_unlock(&lock);

usleep(1000);

}

RETURN:

pthread_mutex_unlock(&lock);

return NULL;

}

int main()

{

if (pthread_mutex_init(&lock, NULL) != 0) {

printf("\n mutex init failed\n");

return 1;

}

pthread_t pthread1, pthread2;

if (pthread_create(&pthread1, NULL, thread1, NULL))

return -1;

if (pthread_create(&pthread2, NULL, thread2, NULL))

return -1;

pthread_join(pthread1, NULL);

pthread_join(pthread2, NULL);

pthread_mutex_destroy(&lock);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值