【问题标题】:About race condtiion关于比赛条件
【发布时间】:2017-04-04 07:25:21
【问题描述】:

当我编译这段代码时,我可以得到这样的结果 enter image description here

代码是这样的

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

void *thread_entry(void *ptr)
      {
int i, j, len;
char *str = (char *) ptr;

len = strlen(str);
for (i = 0; i < 10; i++)   
 {
for (j = 0; j < len; j++) {
    putchar(str[j]);
    sched_yield(); /*to yield CPU*/
                           }
    putchar('\n');
 }
      }

int main()
 {
pthread_t thread1, thread2;
const char *msg1 = "Hello This is Thread 1.";
const char *msg2 = "I am Thread 2.";

pthread_create(&thread1, NULL, thread_entry, (void *) msg1);
pthread_create(&thread2, NULL, thread_entry, (void *) msg2);

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

return 0;
 }

那是代码。我认为是因为 Common Resource,但我不确定。请教我为什么结果是这样的。我真的很欣赏它!

【问题讨论】:

  • 你已经说过了。这里有比赛条件。您应该在临界区周围使用pthread_mutex_lock()pthread_mutex_unlock()
  • @John Is No 谢谢你这么说!!
  • 这段代码是特意设计来突出显示多个线程对输出流的使用。这显然是一项学术活动。请咨询您的教授/导师以获取更多指导。

标签: ubuntu operating-system mutual-exclusion


【解决方案1】:

绝对如你所想。 输出是共享资源,两个线程同时尝试向其推送字符。 事实上,您已经设置了一个 yield ,这将鼓励(但不是控制)线程的进出。

您没有采取任何措施来控制两个线程的交错,并且不可避免地会得到屏幕截图中显示的乱码输出。

在不知道自己要做什么的情况下,无话可说。

【讨论】:

  • 谢谢你,我真的很感激......但我想知道我必须怎么做??
  • 你需要一个 pthreads 教程。这是一个更大的主题,具有一些广泛的基础原则,您不会通过在 Stackoverflow 上提问而轻松获得这些原则。我不知道关于 pthreads 的好教程。您最简单的更改是(如 John 所建议的不)锁定和解锁共享互斥锁以确保每个字符串都完整输出。意志(可能)导致像 ABABABBAAABBABABAB 这样的输出,其中两个线程主要是触发器,但偶尔一个线程在返回之前有两个或多个运行。一个更有趣的练习是确保您得到 ABABABA 输出严格交替。
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 2018-06-14
  • 2019-12-03
  • 1970-01-01
相关资源
最近更新 更多