C实现多线程

时间:2024-03-31 15:06:56
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std; pthread_t thread[]; //线程函数返回值
pthread_mutex_t mut; //互斥锁
int cnt=; void *thread1(void* args)
{
cout<<"T1 Start!"<<endl; for (int i = ; i < ; i++)
{
pthread_mutex_lock(&mut); //加锁,保护共享资源
cnt++;
pthread_mutex_unlock(&mut); //解锁
sleep();
}
cout<<"T1 Wait!"<<endl;
pthread_exit(NULL);
} void *thread2(void* args)
{
cout<<"T2 Start!"<<endl; for (int i = ; i < ; i++)
{
pthread_mutex_lock(&mut); //加锁,保护共享资源
cnt++;
pthread_mutex_unlock(&mut); //解锁
sleep();
}
cout<<"T2 Wait!"<<endl;
pthread_exit(NULL);
} void thread_create(void)
{
pthread_create(&thread[], NULL, thread1, NULL);
cout<<"T1 Create!"<<endl;
pthread_create(&thread[], NULL, thread2, NULL);
cout<<"T2 Create!"<<endl;
} void thread_wait(void)
{
pthread_join(thread[],NULL);
cout<<"T1 Done!"<<endl;
pthread_join(thread[],NULL);
cout<<"T1 Done!"<<endl;
} int main()
{
pthread_mutex_init(&mut,NULL);
thread_create();
thread_wait(); return ;
}

传递多组参数:

struct test{
int no;
char content[MAX] = {};
}; 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);
}