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