lab5-integral - Range SubRange[THREAD_LIMIT]; R /* Create...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <pthread.h> # using namespace std; u //Store the subrange of computation. struct Range { float up; float down; }; } #define RANGE 1000 #define THREAD_LIMIT 4 # pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER; float sum = 0; f void *functionC(void* var) { int i; float SubSum=0; struct Range *SubRange = (struct Range*)var; for (i=int(SubRange->down*RANGE);i<int(SubRange->up*RANGE);i++) SubSum += ((i+i-1)*1.0/(2*RANGE)+1.0/((i+i-1)*1.0/(2*RANGE)+1))*1.0/RANGE; S pthread_mutex_lock( &m_mutex ); sum+=SubSum; s cout<<"SubSum value(" <<SubRange->down<<"," <<SubRange->up<<"):" <<SubSum<<endl; pthread_mutex_unlock( &m_mutex ); p } int main() { int rc; int i; pthread_t thread[THREAD_LIMIT];
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Range SubRange[THREAD_LIMIT]; R /* Create independent threads each of which will execute functionC */ for (i=0;i&lt;THREAD_LIMIT;i++) { SubRange[i].up = (i+1) * 1.0 / THREAD_LIMIT; S SubRange[i].down = i * 1.0 / THREAD_LIMIT; S if( (rc=pthread_create( &amp;thread[i], NULL, &amp;functionC, (void *)&amp;SubRange[i])) ) { //printf(&quot;Thread creation failed: %d\n&quot;, rc1); cout&lt;&lt;&quot;Thread creation failed:&quot;&lt;&lt;rc&lt;&lt;endl; } } for (i=0;i&lt;THREAD_LIMIT;i++) { /* Wait till threads are complete before main continues. */ pthread_join( thread[i], NULL); p } cout&lt;&lt;&quot;Sum of whole range:&quot;&lt;&lt;sum&lt;&lt;endl; c //Release mutex; pthread_mutex_destroy(&amp;m_mutex); p return 0; }...
View Full Document

This note was uploaded on 12/01/2010 for the course CS 2342 taught by Professor Dr during the Spring '10 term at HKU.

Page1 / 2

lab5-integral - Range SubRange[THREAD_LIMIT]; R /* Create...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online