码迷,mamicode.com
首页 > 编程语言 > 详细

C实现多线程

时间:2016-03-30 22:21:49      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

pthread_t thread[2];       //线程函数返回值
pthread_mutex_t mut;   //互斥锁
int cnt=0;

void *thread1(void* args) 
{
     cout<<"T1 Start!"<<endl;  
    
     for (int i = 0; i < 10; i++)
    {   
          pthread_mutex_lock(&mut);      //加锁,保护共享资源
          cnt++;
          pthread_mutex_unlock(&mut);  //解锁
          sleep(1);
     }   
     cout<<"T1 Wait!"<<endl;
     pthread_exit(NULL);
}

void *thread2(void* args)
{
     cout<<"T2 Start!"<<endl;  
    
     for (int i = 0; i < 10; i++)
     {   
           pthread_mutex_lock(&mut);      //加锁,保护共享资源
           cnt++;
           pthread_mutex_unlock(&mut);  //解锁
           sleep(1);
      }   
      cout<<"T2 Wait!"<<endl;
      pthread_exit(NULL);
}

void thread_create(void)
{
     pthread_create(&thread[0], NULL, thread1, NULL);
     cout<<"T1 Create!"<<endl;
     pthread_create(&thread[1], NULL, thread2, NULL);
     cout<<"T2 Create!"<<endl;
}

void thread_wait(void)
{
     pthread_join(thread[0],NULL);
     cout<<"T1 Done!"<<endl;
     pthread_join(thread[1],NULL);
     cout<<"T1 Done!"<<endl;
}

int main()
{
     pthread_mutex_init(&mut,NULL);  
     thread_create();
     thread_wait();

     return 0;
}

 

C实现多线程

标签:

原文地址:http://www.cnblogs.com/LarryGen/p/5338920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!