# multi-thread for computing sum of numbers

Page 1 of 1

## 1 Replies - 793 Views - Last Post: 04 October 2012 - 02:50 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=294307&amp;s=c56164864746ca1ea16fab294123eb61&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 snowingCa

Reputation: 0
• Posts: 2
• Joined: 04-October 12

# multi-thread for computing sum of numbers

Posted 04 October 2012 - 02:45 PM

I have this program in C++, it count sum of one thread,I don't know how to make a sum of multi thread with a program divide the numbers from 1 to N into T groups of consecutive numbers.
For example, it has a 4 group, with N = 15, G = 4. TG1 = (1,2,3,4), G2 = (5,6,7,8), G3 = (9,10,11,12) and G4 = (13,14,15).
The output is ./sum 15 4
Sum (1,15) = 120

--------------------------------------------

#include <iostream>
#include <cstdlib>

using namespace std;

// The sum variable that will be updated by all threads
unsigned long sum;

int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: sum <integer value>" << endl;
exit(1);
}

unsigned long number = atol(argv[1]);
if (number < 0) {
cerr << "Argument " << number << " must be non-negative." << endl;
exit(1);
}

// get the default attributes

// Wait for the thread to exit

cout << "Sum(" << 1 << ", " << number << ") = " << sum << endl;

return 0;
}

// Add the numbers from 1 to n
{

unsigned long num = (unsigned long) number;
for (int i = 1; i <= num; i++)
{
sum += i;
}

}

Is This A Good Question/Topic? 0

## Replies To: multi-thread for computing sum of numbers

### #2 jimblumberg

Reputation: 5447
• Posts: 16,972
• Joined: 25-December 09

## Re: multi-thread for computing sum of numbers

Posted 04 October 2012 - 02:50 PM

Duplicate topic. Topic closed.

Jim