线程

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

char* data[5];//字符指针数组,存人名
int size = 0;//元素数量
//pthread_mutex_t lock;//1 定义互斥
sem_t sem;
void* task(void* p){
  //pthread_mutex_lock(&lock);//3 加锁
  sem_wait(&sem);
  char* name = (char*)p;
  data[size] = name;//data[1] = "gy",cpu归id2
  usleep(100000);//data[1] = "zf",cpu让出来
  size++;
  sem_post(&sem);
  //pthread_mutex_unlock(&lock);//5 解锁
}//size = 3
int main(){
  data[size] = "liubei"; size++;
  sem_init(&sem,0,1);
  //pthread_mutex_init(&lock,0);//2 初始化
  pthread_t id1,id2;
  pthread_create(&id1,0,task,"guanyu");
  pthread_create(&id2,0,task,"zhangfei");
  pthread_join(id1,0); pthread_join(id2,0);
  //pthread_mutex_destroy(&lock);//6 销毁
  sem_destroy(&sem);
  int i;
  for(i=0;i<size;i++) printf("%s\n",data[i]);
}


jion

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>

void* task(void* p){//传参时可以把整数当地址传进来
  int i = (int)p;
  printf("i=%d\n",i);  }
void* task1(void* p){//在线程中保证传入的地址有效
  sleep(1);
  int* pi = (int*)p; printf("%d\n",*pi); }
int main(){
  pthread_t id;  int x = 100;
  int res = pthread_create(&id,0,task,(void*)x);
  if(res) printf("%s\n",strerror(res));//判断出错
  pthread_join(id,0);//main线程等待task
  int* pp = malloc(4); *pp = 100;
  pthread_create(&id,0,task1,(void*)pp);
  free(pp); pthread_join(id,0);
}


#include <stdio.h>
#include <pthread.h>

char* data[5];//字符指针数组,存人名
int size = 0;//元素数量
pthread_mutex_t lock;//1 定义互斥
void* task(void* p){
  pthread_mutex_lock(&lock);//3 加锁
  char* name = (char*)p;
  data[size] = name;//data[1] = "gy",cpu归id2
  usleep(100000);//data[1] = "zf",cpu让出来
  size++;
  pthread_mutex_unlock(&lock);//5 解锁
}//size = 3
int main(){
  data[size] = "liubei"; size++;
  pthread_mutex_init(&lock,0);//2 初始化
  pthread_t id1,id2;
  pthread_create(&id1,0,task,"guanyu");
  pthread_create(&id2,0,task,"zhangfei");
  pthread_join(id1,0); pthread_join(id2,0);
  pthread_mutex_destroy(&lock);//6 销毁
  int i;
  for(i=0;i<size;i++) printf("%s\n",data[i]);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值