C实现多线程

#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;
}

 

传递多组参数:

struct test{
    int no;
    char content[MAX] = {0};
};

int main()
{
    struct test t1;
    pthread_create(thread, NULL, func_thread, &t1);
    pthread_join(thread, NULL);

}


void *func_thread(void* args) 
{
     struct test* t1;
     t1 = (struct test*)args; 
    
     // *****

     pthread_exit(NULL);
}

 

转载于:https://www.cnblogs.com/LarryGen/p/5338920.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值