目录
一、知识点
1.线程优点
(1)即使是单核系统,多线程也可以为本进程利用更多CPU时间;
(2)线程少浪费系统资源,进程费时保护现场恢复现场
2. 结束进程 exit(-1)
结束线程 pthread_exit() 、return
gcc -lsqlite3 、 gcc -lm 、 gcc -lpthread
3.主线程、公共线程流程图
(1)pthread_create() (2)pthread_exit() (3)pthread_join()
4.线程同步方式:
介绍Mutex和Conditions,信号量(信号灯了解即可)
5.互锁信号量mutex:四种属性,NULL默认为普通
recursive 普通
timed 嵌套(可以上多把锁,但只能是一个线程上的)
理解:??自己可以自行车锁三把,但小偷要是加一把的话就打不开了??
6.条件变量 unlock-> wait-> lock
7.网络7层和Linux四层划分
直接体现:数据多层封装
二、代码练习
1.线程
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char message[] = "hello world";
void * tid_work(void * arg)
{
printf("thread function in running argument is %s \n", (char *)arg);
sleep(3);
strcpy(message, "Bye");
pthread_exit("thank you for your CPU time");
}
int main()
{
pthread_t tid;
int ret;
void * thread_val;
ret = pthread_create(&tid, NULL, tid_work, (void *)message);
if (ret != 0)
{
perror("create thread error");
exit(-1);
}
printf("waiting for thread to finish...\n");
ret = pthread_join(tid, &thread_val);
if (ret != 0)
{
perror("thread join error");
exit(-1);
}
printf("thread joined, it returned %s\n", (char *)thread_val);
printf("message is now: %s\n", message);
return 0;
}
2.条件变量
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 16
#define OVER -1
struct prod
{
int buffer[BUFFER_SIZE];
pthread_mutex_t lock;
pthread_cond_t notempty;
pthread_cond_t notfull;
int readpos, writepos;
};
struct prod buf;
void init(struct prod * b)
{
pthread_mutex_init(&b->lock, NULL);
pthread_cond_init(&b->notempty, NULL);
pthread_cond_init(&b->notfull, NULL);
b->readpos = b->writepos = 0;
}
void put(struct prod *b, int data)
{
pthread_mutex_lock(&b->lock);
if(( b->writepos + 1) % BUFFER_SIZE == b->readpos)
{
pthread_cond_wait(&b->notfull, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= BUFFER_SIZE)
{
b->writepos = 0;
}
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prod * b)
{
int data;
pthread_mutex_lock(&b->lock);
if (b->readpos == b->writepos)
{
pthread_cond_wait(&b->notempty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos = (b->readpos + 1) % BUFFER_SIZE;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
void * customer(void)
{
int d;
while(1)
{
d = get(&buf);
if (OVER == d)
{
break;
}
printf("---->%d\n", d);
}
return NULL;
}
void * producer(void)
{
int n;
for (n = 0; n < 20; n++)
{
printf("%d----->", n + 1);
put(&buf, n + 1);
}
put(&buf, OVER);
return NULL;
}
int main()
{
pthread_t th_p, th_c;
init(&buf);
pthread_create(&th_p, NULL, (void *)producer, NULL);
pthread_create(&th_c, NULL, (void *)customer, NULL);
pthread_join(th_p, NULL);
pthread_join(th_c, NULL);
return 0;
}