Fork me on GitHub

#include  <iostream>
#include <pthread.h>
using namespace std;
int sum=0;
void * add(void *);
pthread_mutex_t mut;
int main()
{
    pthread_t thread[10];
    int num;
    long count;
    cout<<"Enter the number of thread (1-10):";
    cin>>num;
    cout<<"Enther the number to count to:";
    cin>>count ;
    for (int x=0;x<num;x++)
    {
        pthread_create(&thread[x],NULL,add, (void*) count);
                   
     }

          for (int x=0;x<num;x++)
              pthread_join(thread[x],NULL);  //ensure every thread terminated
     
         cout<<sum<<endl;
         return 0;

}

void *add(void *count)
{
    long num;
    num=(long) count;
//    pthread_mutex_lock(&mut);
    for (long x=1;x<=num;x++)
    {
        sum+=x;
        //cout<<sum<<'\t'<<x<<endl;
    }
    //pthread_mutex_unlock(&mut);
}
posted on 2014-07-25 15:25  huashiyiqike  阅读(173)  评论(0编辑  收藏  举报