排序两个线程的执行 [英] Ordering the execution of two threads

查看:23
本文介绍了排序两个线程的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写两个线程,第一个从控制台读取一个字符串,第二个输出其中的字符数.

I wanna write two threads, first will read a string from the console, and the second will output the number of characters in it.

为此,我必须设置线程的执行顺序,先读,再写.

To do so, I have to set the order of executing the threads, reading first, writing second.

我还希望同时执行一个线程.

Also I want one thread to execute at the time.

我该怎么做?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *printCharacterNumber(void *ptr);
void *readMessage(void *ptr);

int main()
{
   pthread_t thread1, thread2;
   int iret1, iret2;

   iret1 = pthread_create(&thread1, NULL, printMessage, NULL);
   iret2 = pthread_create(&thread2, NULL, printCharacterNumber, NULL);

   pthread_join(thread1, NULL);
   pthread_join(thread2, NULL);

   return 0;
}

void *readMessage(void *ptr)
{
   char *message;
   fscan("%s", &message);
}

void *printCharacterNumber(void *ptr)
{
   printf("%s", message); // I'll add counting when it will work
}

推荐答案

genine (pthread) 线程最大的兴趣在于支持并行执行(利用大多数笔记本电脑和台式机拥有的几个内核)...阅读一些 pthread 教程 ...

The biggest interest of genine (pthread) threads is to enable parallel execution (taking profit of the several cores most laptops and desktops have)... Read some pthread tutorial ...

您可能想要使用障碍.阅读更多关于 pthread_barrier_wait &pthread_barrier_init

You may want to use barriers. Read more about pthread_barrier_wait & pthread_barrier_init

如果你想序列化一些计数器,你可以使用(使用最近的 C11 编译器,例如 GCC 4.9)一些 原子内置函数,或者更常见的是 mutex,参见 pthread_mutex_init &pthread_mutex_lock 等等......:

If you want to serialize some counter, you could use (with recent C11 compilers, e.g. GCC 4.9) some atomic builtins, or more usually a mutex, see pthread_mutex_init & pthread_mutex_lock etc....:

 static pthread_mutex_t mtx = PTHREAD_MUTEX_INIT;

 static long counter;

 void increment_serialized_counter (void) {
     pthread_mutex_lock(&mtx);
     counter++;
     pthread_mutex_unclock(&mtx);
 }

 long get_serialized_counter (void) {
    long r = 0;
    pthread_mutex_lock(&mtx);
    r = counter;
    pthread_mutex_unclock(&mtx);
    return r;
 }

如果是静态的,您可能应该为 message 变量使用互斥锁!

You probably should use a mutex for your message variable, if it was static!

这篇关于排序两个线程的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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