#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
typedef struct lxj
{
int a;
int b;
} lxj;
void *fun(void *arg)
{
lxj *p = (lxj *)arg;
printf("%d\n", p->a);
printf("%d\n", p->b);
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
lxj abc;
abc.a = 1;
abc.b = 2;
pthread_t thread;
// 第四个参数 可以是一个指向任意类型数据的指针
pthread_create(&thread, NULL, fun, &abc);
pthread_join(thread, NULL);
return 0;
}
使用pthread_exit()
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
typedef struct lxj
{
int a;
int b;
} lxj;
void *fun(void *arg)
{
lxj *p = (lxj *)arg;
printf("%d\n", p->a);
printf("%d\n", p->b);
}
int main(int argc, char const *argv[])
{
lxj abc;
abc.a = 1;
abc.b = 2;
pthread_t thread;
// 第四个参数 可以是一个指向任意类型数据的指针
pthread_create(&thread, NULL, fun, &abc);
pthread_exit(NULL); // 线程退出 等待所有线程结束后才终止
return 0;
}
线程打印奇数和偶数
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
void *fun(void *arg)
{
for (int i = 2; i <= 100; i += 2)
{
printf("%d\n", i);
}
}
int main(int argc, char const *argv[])
{
pthread_t tid;
pthread_create(&tid, NULL, fun, NULL);
for (int i = 1; i <= 100; i += 2)
{
printf("%d\n", i);
}
pthread_join(tid, NULL);
return 0;
}
资源竞争
// 互斥锁只能被一个线程所使用
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
pthread_mutex_t mutex;
// pthread_mutex_t 互斥锁的类型
void *fun(void *arg)
{
pthread_mutex_lock(&mutex); // 上锁
// 上锁
int a = 100;
int b = 20; // a 和 b为临界区的临界资源
printf(" %d a %d b 的I am %s\n", a, b, (char *)arg);
sleep(2);
// 上锁和解锁之间为临界区
pthread_mutex_unlock(&mutex); // 解锁
// 解锁
return NULL;
}
void *fun2(void *arg)
{
pthread_mutex_lock(&mutex); // 上锁
// 上锁
int a = 10000;
int b = 20000; // a 和 b为临界区的临界资源
printf(" %d a %d b 的I am %s\n", a, b, (char *)arg);
sleep(2);
// 上锁和解锁之间为临界区
pthread_mutex_unlock(&mutex); // 解锁
// 解锁
return NULL;
}
int main(int argc, char const *argv[])
{
/* code */
/*
锁初始化
锁的销毁
*/
pthread_mutex_init(&mutex, NULL);
// 初始化锁
pthread_t tid;
pthread_t tid2;
char *p = "sddsdsdsdsdsdsd";
pthread_create(&tid, NULL, fun, p);
pthread_create(&tid2, NULL, fun2, p);
pthread_join(tid, NULL); // 等待线程结束
pthread_mutex_destroy(&mutex);
// 销毁锁
return 0;
}