多线程程序示例 [英] Multi-threaded program example

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

问题描述

编写一个多线程程序,用于计算数字列表的总和。该程序将在运行时在命令行上传递一系列数字(确切地为5个数字),然后将创建一个工作线程,该线程将找到5个值的总和,而父线程将输出(打印)总和工作线程退出后的值。表示总和的变量将全局存储。例如,假设您的程序传递整数:7 8 9 10 11程序将显示以下输出:总和为45.



我解决了我将答案放在最后但是示例的第2部分我无法理解它并且无法解决它请帮助:



在(a)部分修改你的代码在两个线程之间划分总和作业。每个线程将传递5个数字,然后第一个线程将仅总结偶数(即前一个例子中的8和10),而第二个线程将总和奇数(即7,9,11)前面的例子)。求和是在相同的总和全局变量上完成的。另一个称为计数器的全局变量用于计算已经总结的数字(偶数或奇数)。计数器的值递增,然后每次将数字(偶数或奇数)添加到和变量时打印出来。一旦工作线程退出,父线程将输出(打印)最终的总和值和最终的计数器值。程序将显示上一个示例的以下输出(请注意TN为1或2):计数器值为1并按螺纹增量TN



我尝试过:



Write a multithreaded program that calculates the sum of a list of numbers. This program will be passed a series of numbers (5 Numbers exactly) on the command line at the run time and will then create one worker thread that will find the sum of the 5 values, while the parent thread will output (print) the sum value once the worker thread has exited. The variable representing the sum will be stored globally. For example, suppose your program is passed the integers: 7 8 9 10 11 The program will show the following output: The sum is 45.

and i solved that i will put the answer in the last but the part 2 of the example i cant understand it and cant solve it please help:

Modify your code in part (a) by dividing the sum job between two threads. Each thread will be passed the 5 numbers, then the first thread will sum up the even numbers only (i.e. 8 and 10 in the previous example), while the second thread will sum up the odd numbers (i.e. 7, 9, 11 in the previous example). The summation is being done on the same sum global variable. Another global variable called counter is used to count the numbers (even or odd) that have been summed up. The value of counter is incremented and then printed out every time a number (even or odd) is added to the sum variable. The parent thread will output (print) the final sum value and the final counter value once the worker threads have exited. The program will show the following output for the previous example (note that TN is either 1 or 2) : The counter value is 1 and incremented by thread TN

What I have tried:

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

/*Error handling for pthread_create and pthread_join*/
/*from the pthread_create man page*/
#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

/* # of running threads */
volatile int running_threads = 0;

pthread_t thread[1]; /*Descriptors for our 3 threads*/

int numOfElements;/*Total # of elements from the user*/

struct Results{ /*Struct to hold the statistical results*/
	

	int sum;

}Results;



/*This function finds the average of an array*/
void *findsum(void *array_ptr){
	
	int i;	 /*counter*/

	int *elements = (int*)array_ptr; 	/*re reference void array pointer*/

	for(i = 0; i < numOfElements; i++){		/*iterate through array*/

		Results.sum += elements[i];		/*add element @ i to average*/

	}


	running_threads -= 1;	/*Decrement running threads counter*/

return NULL;

}

/* This method accepts a int n(initial size of array) and
   pointer to an array and returns # of elements in the array
*/
int getArrayInput(int n, int *array_ptr){
		
		int input;/*Store user input */

		int numberOfElements = 0;/*Number of Integers inputed*/

    	printf("Creating Dynamic Array...\n-\n");

		for(;;){  /*infinite loop*/

    		printf("Enter a positive value:\nNegative Number to Stop\n-\n");
   
    		//Get Int from console, store at address of input

			if (scanf("%d",&input) != 1){

				printf("\nOops that wasn't an Integer\nlets try filling the array again\nRemember INTEGERS only!\n");

				exit(EXIT_FAILURE);
			
			}

    		if (input >= 0){ 

       		 	if (numberOfElements == n){

          	  	  n += 1; //Make room for the current input
            		
          		  array_ptr = realloc(array_ptr, n * sizeof(int));//realloc array and set pointer
            
       			 }

        		array_ptr[numberOfElements++] = input;//Store input at next empty element
    
    		} else {
        
       		 printf("\nNumber of Integers: %d\n", numberOfElements);
       
       		 break;

   				 }

			}

	return numberOfElements;
	
		}


	
/*This function creates the 3 threads we need and supplys
  error catching for pthread_create, it could be 
  modified easily to create any # of threads automatically
*/
void createThreads(int *array_ptr){
	
	int s; /*error #*/
	 /*Create a thread and passing in the function to begin 
	 exectuing as well as that functions required arguments*/ 
 
 
	 /*Create a thread and passing in the function to begin 
	 exectuing as well as that functions required arguments*/ 
	 s = pthread_create(&thread[2], NULL, findsum, (void *)array_ptr);
	 		 
		 if (s != 0){

           handle_error_en(s, "pthread_create");
       	
       	 }
			
			running_threads += 1;

}

/* The main function initialiazes the dynamic array as well
   as allocating space for it, Then it creates, using pthread_create,
   1 threa to calculate the min, 
 */
int main(){

	int n = 1; /* Initial Array Size*/

	int *array_ptr = malloc(n * sizeof(int));/*Initialize array pointer*/
		
		 /*get an n sized array of elements from the user and save count*/
		 numOfElements = getArrayInput(n, array_ptr);
		
		 createThreads(array_ptr);
		
	    	while(running_threads>0){	/*Wait for each thread to decrement*/
	
				sleep(1);

			}

	

		/*Prompt the user with our results*/
		printf("\nThe sum is %d\n",Results.sum);

	return(0);

}

推荐答案

您需要创建两个线程,每个线程都有不同的任务:一个添加偶数一个加奇。你需要添加全局变量,并提供锁定以确保两个线程不会在使用它时弄得一团糟。

你还需要提供一个信号机制来获取主要变量线程显示当前(修订的)计数。



老实说,如果你试图通过查找示例并尝试做到这一点来学习编码,那么你很漂亮浪费你的时间。这就像试图通过偷车和高速公路上的错误方式来学习驾驶。你可能会学到很多东西,你可能会崩溃很多次,但是你不会学习如何平行停车,或者在环形交叉路口做什么!即使经过几十次旅行,你肯定不会是一个称职的司机...

发展是一样的:自学只是意味着你不知道你不是知道 - 而且很多都可以让你的工作变得更轻松。回到汽车比喻,假设你偷了一个变速杆/手动变速箱,但你甚至不知道离合器存在,更不用说用它做什么了。学习驾驶书籍或更好的课程将教你这些事情 - 学习编码方式也会填补空白更好​​。
You need to create two threads, each with a different task: one adds even numbers, one add odd. You will need to add the global variable, and provide locking to ensure that the two threads don;t get in a mess while using it.
You will also need to provide a signaling mechanism that gets the main thread to display the current (revised) count.

To be honest, if you are trying to learn to code by finding examples and trying to do them, you are pretty much wasting your time. That's like trying to learn to drive by stealing a car and driving the wrong way up the motorway. You may learn a lot, you will probably crash a significant number of times, but you won't learn how to parallel park, or what to do at a roundabout! And you certainly won't be a competent driver, even after a few dozen trips...
Development is the same: "learning on your own" just means you have no idea what you don't know - and a lot of it could make your job a lot easier. Back to the car analogy, assume you steal a stick shift / manual gearbox but you don't even know that the clutch exists, much less what to do with it. Learning to drive from a book or better a course will teach you those things - and learn to code the same way will also "fill in the gaps" a lot better.


这篇关于多线程程序示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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