如何解决这个基本线程程序中的问题? [英] how can I solve the problem in this basic thread program?

查看:72
本文介绍了如何解决这个基本线程程序中的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这个程序的逻辑。当我运行程序时

I dont understand the logic of this program . when I run the program

& gcc sample.c -pthread
& ./a.out





我无法得到正确的结果。有时我可以在线程中看到



I cannot get the correct result. Sometimes I can see the result of

printf

func的结果,有时候我不能。可能是什么原因?



func in thread and sometimes I cannot.What reason It can be?

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

void *thrFoo(void *arg){

	int x = *((int *)arg) ;

	printf("res : %d\n",x*5 );


}

int main()
{
	
	pthread_t thr;

	int a = 4 ;

	pthread_create(&thr,NULL,thrFoo,&a);


	printf("I am trying to understand the logic of\n");
	printf("Threads\n");


	return 0;
}

推荐答案

因为有时候,你的线程有机会在应用程序终止之前运行,有时它不会'' t。



想一想:你开始一个线程,打印一些行并终止你的应用程序。终止时,与其关联的所有线程也将终止。所以有时候,不同核心上有空间,你的线程会立即运行。其他时间没有,它排队等候。但是你的应用程序结束了,所以线程在它有机会做任何事情之前终止。



尝试在退出main函数之前从控制台添加一个读取,或者等待新线程先终止。
Because sometimes, your thread gets a chance to run before your application terminates, and sometimes it doesn''t.

Think about it: You start a thread, print some lines and terminate your application. When you terminate, all thread associated with it are also terminated. So sometimes, there is space on a different core, and your thread runs immediately. Other times there isn''t, and it gets queued. But then you app ends, so the thread is terminated before it gets a chance to do anything.

Try adding a read from the console before you exit the main function, or wait for the new thread to terminate first.


除了 OriginalGriff 的回复之外,请参阅加入和分离线程 [ ^ ]。
In addition to OriginalGriff''s reply, see "Joining and Detaching Threads"[^].


主进程应该等待线程结束

add
Main process should wait for thread to end
add
pthread_join(thr,NULL);

后线程。



after thread.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
 
void *thrFoo(void *arg){
 
	int x = *((int *)arg) ;
 
	printf("res : %d\n",x*5 );
 

}
 
int main()
{
	
	pthread_t thr;
 
	int a = 4 ;
 
	pthread_create(&thr,NULL,thrFoo,&a);
        pthread_join(thr,NULL); //Main Process should wait for thread to end
 

	printf("I am trying to understand the logic of\n");
	printf("Threads\n");
 

	return 0;
}


这篇关于如何解决这个基本线程程序中的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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