程序在单独的线程上打印奇数和偶数 [英] program to print odd numbers and even numbers on seperate threads

查看:96
本文介绍了程序在单独的线程上打印奇数和偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用pthreads进行编程. 我该如何编写一个程序来在单独的线程上打印奇数和偶数.

I am learning programming using pthreads. How can I write a program to print odd numbers and even numbers on separate threads.

推荐答案

您需要两个同步对象,例如信号量或条件变量.这个想法是线程A在打印之前请求信号A,而在线程B进行相反操作之后则释放信号B.

You need two synchronization objects such as a semaphore or a condition variable. The idea is that thread A requests semaphore A before it prints and releases semaphore B after while thread B does the opposite.

这个想法是,线程A请求信号量A之后,它将信号量降低为0.下次请求信号量A时,它将阻塞,直到线程B释放信号量为止.

The idea is that after thread A requests semaphore A, it will drop the semaphore to 0. The next time it requests semaphore A it will block until thread B releases the semaphore.

在伪代码中,这看起来像:

In pseudo code, this looks like:

initialization:
    // set semA to 1 so that the call to sem_wait in the
    // even thread will succeed right away
    sem_init(semA, 1)
    sem_init(semB, 0)

even_thread:
   to_print = 0;

   loop:
       sem_wait(semA);

       write(to_print);
       to_print += 2

       sem_post(semB)

odd_thread:
    to_print = 1

    loop:
        sem_wait(semB)

        write(to_print)
        to_print += 2

        sem_post(semA)

由于您想自学线程编程,因此我将把它转换为实际的pthreads代码.

Since you want to teach yourself threads programming, I'll leave it to you to convert this into actual pthreads code.

这篇关于程序在单独的线程上打印奇数和偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆