mutex是确保两个线程(包括父线程)不会在同一时刻操作同一内存的方法。由此逻辑可以完成两个线程之间的数据发送,父线程拥有一个数据结构的缓存和与它相关的读写计数器。子线程可以从缓存中获得数据和写数据。当子线程读数据的时候,它填充缓存,并且更新计数器。父线程可以监视缓存计数器的值,并报告数据是否准备好:是或否,还是错误。并不是所有得系统都可以确认缓存可以被写以便程序可以去写数据。无论如何,当两个线程进行通讯时,采用一种锁机制以确保数据总是能够被正常读写是非常必要的。mutex就是这样的一种机制。它确保对于同样内存的操作是相互排斥的。
mutex结构和函数
不要拷贝mutex. 一个 mutex 声明的例子:
typedef struct input_data { pthread_mutex_t mutex; //控制对 sharedint的读写
int sharedint;
} input_data; input_data datain = {PTHREAD_MUTEX_INITIALIZER, 0}; |
|
条件变量
条件变量用于传达带有一个mutex的共享数据的状态信息。当一个线程等待一个条件变量得时候,它将处于阻塞状态。
- pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
- int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *condattr);
- int pthread_cond_destroy (pthread_cond_t *cond);
- int pthread_cond_wait (pthread_cond_t *condition, pthread_mutex_t *mutex);
- int pthread_cond_timedwait (pthread_cond_t *condition, pthread_mutex_t *mutex, struct timespec *expiration);
- int pthread_cond_signal (pthread_cond_t *condition);
- int pthread_cond_broadcast (pthread_cond_t *condition);
不要拷贝共享变量。一个关于共享变量声明的例子:
typedef struct input_data
{
pthread_mutex_t mutex; //控制对 sharedint的读写
pthread_cond_t condition; //确定sharedint的变化
int sharedint;
} input_data;
input_data datain = {PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, 0};
google_ad_client = "pub-2416224910262877"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_channel = ""; google_color_border = "E1771E"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000";