【发布时间】: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” -0到N - 1。
标签: c linux multithreading