【问题标题】:Pass a simple integer to a thread’s start function at thread creation time在线程创建时将一个简单的整数传递给线程的启动函数
【发布时间】:2016-04-08 11:30:33
【问题描述】:

代码是示例,我需要做的是修改。

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

void  *my_function (void*); // Function for the thread 

int main ()
{
    pthread_t   my_thread ; // Declare a thread identifier
    int  rc1, x = 7; 

    // Create my_thread 
    if ( (rc1 = pthread_create (& my_thread, NULL,  & my_function,  (void*) &x)))
    {
        printf ("Error in creating thread %d\n", rc1);
    }

    pthread_join ( my_thread, NULL); // wait for thread to exit

    return (0); // exit the main function
}


// The my_thread is created with my_function() which accepts an argument 
void  *my_function(void* arg)
{
    int i = *(int*)arg;

    printf ("The argument which this thread received is %d \n", i ) ; 

    pthread_exit (NULL) ;    // thread exits
}

问题是:在线程创建时将一个简单的整数传递给线程的启动函数。但是我不知道如何将一个简单的整数传递给线程的启动函数,也不知道什么是线程创建时间。

【问题讨论】:

  • 线程创建时间是你调用pthread_create()的时间。鉴于名称,这可能会让您感到惊讶,但是您已经拥有了。目前您正在将一个指向整数的指针传递给线程,这比直接传递整数要干净一些。
  • @EOF 虽然在问题中通过引用传递int 更清晰,但这确实意味着调用pthread_create 的线程必须保留传递的变量的值,直到从新线程可以安全地更改值或销毁变量。例如,for 循环启动 N 线程,其中每个线程都传递其“id” - 0N - 1

标签: c linux multithreading


【解决方案1】:

如果你的实现有intptr_t(大部分都有),你可以修改代码如下:

int  rc1; 
intptr_t x = 7
...
pthread_create (&my_thread, NULL, &my_function, (void*)x));
...
void* my_function(void* arg)
{
    intptr_t i = (intptr_t)arg;
...

【讨论】:

  • 我没有投反对票,但关于[u]intptr_t 的保证是您可以通过[u]intptr_t 往返void*,而不是相反:void* -&gt; [u]intptr_t -&gt; void* 产生一个指针比较等于初始指针,但[u]intptr_t -&gt; void* -&gt; [u]intptr_t 不保证[u]intptr_ts 的相等性。
  • @EOF,我也想过。但是我看不出 void -> ptr -> void 在理论上是如何有效的,但 ptr->void->ptr 不是。基本及物性(我想这是一个正确的词)需要它。好吧,没有通过某种查找表进行上述转换的编译器。
  • 其实很简单:想象一下指针是 32 位,整数(包括[u]intptr_t)是 64 位的架构。现在任何转换为​​[u]intptr_t 的指针显然都可以返回,但是任意的[u]intptr_t 不能从void* 转换回来。
  • 是的,不知何故,这个简单的事实并没有发生在我身上。我想,downvote 是应得的。但是,反对者可以解释原因。
猜你喜欢
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2012-06-09
  • 2013-07-20
  • 2022-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
相关资源
最近更新 更多