我的问题与C中的线程编程有关。
我的问题是我只想在我的main
程序中创建两个线程。这两个线程应该按顺序工作,这意味着我的第一个线程应该首先执行(任何线程的其他语句都不应该执行)。第一线程应该有完全的控制权。在第一个线程完成之前,不应该执行任何其他线程的其他语句,甚至是main
程序语句。
在第一个线程完成后,第二个线程应该以与第一个线程类似的方式执行。
在那之后,我的main应该会执行。
我知道你可以说我为什么要这样做,因为这件事可以通过创建两个函数并按顺序调用它们来实现,但为了学习和实验,我想借助线程来完成它。
我用C编写了一些代码,如下所示:
void* fun()
{
printf("\nThe thread 1 is running");
}
void* van()
{
printf("\nthread 2 is running ");
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
pthread_join(t2,NULL);
}
程序运行得很好,但我不理解函数pthread_join()
的工作原理。
当我稍微修改代码时,如下所示:
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_join(t2,NULL); // Change
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
}
现在,当我运行代码时,它显示了一个分段错误。
现在我的问题如下:
pthread_create()
函数中的属性参数是什么?我们为什么要使用它们呢?线程的默认属性是什么?请举例说明。pthread_create()
函数中的参数是什么?我们为什么要使用它们?线程的默认参数是什么?请举例说明。pthread_join()
到底是如何工作的?当我的代码以t2
作为第一个参数调用main中的pthread_join()
时,这意味着什么?这是不是意味着main应该挂起它的执行,直到t2执行完成,或者其他什么?,,
pthread_join()
中的第二个参数是什么?我们为什么要使用它?它的默认值是什么?请用示例或代码解释。发布于 2011-06-03 13:22:13
学习POSIX线程的最好资源是https://computing.llnl.gov/tutorials/pthreads/
发布于 2011-06-03 13:30:36
pthread_create
中的属性的类型为pthread_attr_t
。它保存有关线程的信息,包括线程的内存地址起始位置和堆栈大小等信息。大多数情况下,你不需要使用这个参数。pthread_create
中的arg被作为唯一的参数传递给start_routine
函数。这是一种黑客行为。由于指针可以指向任何对象( int、数组、结构等),因此可以通过传递指向要传递的所有数据的指针来传递参数。大多数情况下,人们最终会使用结构。线程没有默认参数。如果不想传入任何内容,只需将arg
指定为NULL即可。举个例子:
struct arguments
{
int something;
char* anotherArg;
short stillAnotherArg;
}
void* fun(void* arg)
{
struct arguments *my_args = (struct arguments*)arg;
printf("You said: %s\n", my_args->anotherArg); // Will print "You said: Hello there"
...
}
int main()
{
pthread_t t1;
struct arguments my_args;
my_args.something = 5;
my_args.anotherArg = "Hello there";
my_args.stillAnotherArg = 42;
pthread_create (&t1,NULL,fun, &my_args);
...
}
pthread_join
将阻塞调用方,直到指定的线程具有finished.pthread_join
的第二个参数允许您在线程执行完成后捕获该线程的返回值。每个线程返回一个void*
,第二个参数允许您指定返回值的存储位置。举个例子:
void* fun(void* arg)
{
...
return NULL; // not very exciting, but I don't want to get
// into memory management problems right now
}
int main()
{
...
void* theReturnValue;
pthread_join(t2, &theReturnValue);
printf("fun returned %p\n", theReturnValue); // will print "fun returned 0x0"
// which is NULL
}
最后,它分段错误的原因是因为您正在等待一个尚未定义的线程。
发布于 2018-06-03 10:59:37
您可以通过包含omp.h来使用omp库。它很容易使用。您可以使用以下指令创建并行部分
#pragma omp parallel
{
// PARALLEL Code
}
使用omp_set_num_threads(2);
设置线程数,然后使用omp_get_thread_num();
获取线程的id
示例:
omp_set_num_threads(2);
#pragma omp parallel
{
printf("thread %d said hello", omp_get_thread_num());
}
https://stackoverflow.com/questions/6223216
复制相似问题