Gol*_*olu 2 c multithreading pthreads
我的问题与C中的线程编程有关.
我的问题是我只想在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);
}
Run Code Online (Sandbox Code Playgroud)
该程序工作正常,但我不理解该功能的工作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");
}
Run Code Online (Sandbox Code Playgroud)
现在,当我运行代码时,它显示了一个分段错误.
现在我的问题如下:
pthread_create()函数中的属性参数是什么?我们为什么要使用它们?线程的默认属性是什么?请举例说明.pthread_create()什么?为什么我们使用它们?线程的默认参数是什么?请举例说明.pthread_join()实际上是如何工作的?当我的代码pthread_join()在main中t2作为第一个参数调用时,它意味着什么.这是否意味着主要应该暂停执行直到t2执行完成或其他什么?pthread_join()什么?我们为什么用它?它的默认值是多少?请用示例或代码解释.attr参数指向pthread_attr_t结构,其内容在创建线程时用于确定新线程的属性; 使用pthread_attr_init(3)和相关函数初始化此结构.如果attr为NULL,则使用默认属性(source)创建线程.
参数传递给您的线程函数.这是将数据传递给线程的最佳方式(与使用全局变量相反,例如).
是的,pthread_join等到线程完成.这就是为什么你的程序pthread_join在启动线程之前调用失败的原因,因为t2在那一点上包含了垃圾.
如果retval不为NULL,则pthread_join()将目标线程的退出状态(即目标线程提供给pthread_exit(3)的值)复制到*retval指向的位置.如果目标线程被取消,则PTHREAD_CANCELED被置于*retval中.(来源).
即,您可以使您的线程功能通知您其执行结果.
鉴于此,您的线程创建可能如下所示:
struct th_arg{
...
};
static void th_work(struct th_arg* a){
//...some work
if (success) pthread_exit(EXIT_SUCCESS)
else pthread_exit(ERROR_CODE);
}
int main(){
int t1,t2;
struct th_arg[2];
int codes[2];
// initialize th_arg2
pthread_create(&t1, NULL, th_work, th_arg+0, th_arg+0);
pthread_create(&t2, NULL, th_work, th_arg+1, th_arg+1);
pthread_join(t1, codes+0);
pthread_join(t2, codes+1);
if (codes[0] == EXIT_SUCCESS && codes[1] == EXIT_SUCCESS){
...
}
}
Run Code Online (Sandbox Code Playgroud)