带有 pthread 函数的静态存储 [英] static storage with pthread functions

查看:49
本文介绍了带有 pthread 函数的静态存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习一些多线程程序,但我无法弄清楚这个输出背后的逻辑.

I was practicing some multithreaded programs, but I could not figure the logic behind this output.

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

int print_message(void* ptr);

int main()
{
pthread_t thread1,thread2;
char *mesg1 = "Thread 1";
char *mesg2 = "Thread 2";

int iret1, iret2;

pthread_create(&thread1, NULL, print_message, (void *)mesg1);
pthread_create(&thread2, NULL, print_message, (void *)mesg2);

pthread_join(thread1,(void*)&iret1 );
pthread_join(thread2, (void*)&iret2);

printf("Thread 1 return : %d\n", (int)iret1);
printf("Thread 2 return : %d\n", (int)iret2);
return 0;

}

int print_message(void *ptr)
 {
char *mesg;
static int i=0;
mesg = (char *)ptr;
printf("%s\n",mesg);
i++;
return ((void*)i);

}

我期待输出

Thread 1
Thread 2
Thread 1 return : 1
Thread 2 return : 2

但我得到了输出

Thread 1
Thread 2
Thread 1 return : 0
Thread 2 return : 2

有人可以向我澄清一下吗?并请指出pthread函数使用中是否有错误.

Could some please clarify this to me ? And please point if any errors in usage of pthread functions.

推荐答案

变量 i 在两个线程之间共享,因为它是 static.在多个线程之间修改变量的行为是未定义的,因此,实际上,您获得的输出和您想要获得的输出都是错误的",因为编译器没有义务将其提供给您.事实上,我能够根据我使用的优化级别来改变输出,并且毫无疑问会因平台而异.

The variable i is shared between both threads because it is static. The behaviour of modifying a variable between multiple threads is undefined, so, in fact, both the output you get and the output you want to get are "wrong" in the sense that the compiler is under no obligation to give it to you. In fact, I was able to get the output to change depending on the optimisation level I used and it will undoubtedly be different based on the platform.

如果你想修改i,你应该使用互斥锁:

If you want to modify i, you should use a mutex:

int print_message(void *ptr)
{
  static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  char *mesg;
  static int i=0;
  int local_i;

  mesg = (char *)ptr;
  printf("%s\n",mesg);
  if (pthread_mutex_lock(&mutex) == 0) {
    local_i = ++i;
    pthread_mutex_unlock(&mutex);
  }
  return ((void*)local_i);
}

如果您不使用互斥锁,您将永远无法确定获得您认为应该获得的输出.

If you do not use a mutex, you will never be sure to get the output you think you should get.

这篇关于带有 pthread 函数的静态存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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