android中和c++中生產者和消費者模式

首先上代碼,android

package com.wmz.helloworld;
import java.util.Random;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Demo extends android.app.Activity {
	private class Token {
		private String flag;
		public Token() {
			setFlag(null);
		}
		public void setFlag(String flag) {
			this.flag = flag;
		}
		public String getFlag() {
			return flag;
		}
	}
	private Token token = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.demo);
		Button btn = (Button) findViewById(R.id.button1);
		token = new Token();
		if(token.getFlag() ==null)
			Log.v("A","the token flag value is null");
		else
			Log.v("A","the token flag value is"+token.getFlag());
		btn.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WorkThread workthread = new WorkThread();
				workthread.start();	
				Random r=new Random();
				for (int i = 0;i<10; i++) {
					try {						
						Thread.sleep((r.nextInt(9)+1)*1000);		//增加不確定性,至少睡眠1秒
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (token) {
						token.setFlag("wangmz"+Integer.toString(i));
						token.notifyAll();
						Log.v("Main",Integer.toString(i));
					}					
				}
			}
		});		
	}
 
 
	private class WorkThread extends Thread {
		@Override
		public void run() {
			Random r=new Random();
			while (true) {				
//				try {
//					Thread.sleep((r.nextInt()+1)*1000);//可能在sleep的時候其他線程執行notify()。但此時對這個線程不起作用。所以結果不會按順序出現
//				} catch (InterruptedException e1) {
//					e1.printStackTrace();
//				}
				synchronized (token) {
						try {
							token.wait();
							Log.v("Main", "the value is " + token.getFlag());
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
				Log.v("work","while!!");
			}
		}
	}
}

c++中實現

std::mutex img_mutex_;
std::condition_variable img_cv_;

cv::Mat camera::grapPicture()
{
    std::unique_lock<std::mutex> lk(img_mutex_);
    img_cv_.wait(lk,[this]{return this->isReady_;});
    cv::Mat temp= img_.clone();
    std::cout<<"grap picture,img size:"<<temp.rows<<","<<temp.cols<<std::endl;
    isReady_=false;
    return temp;
}


void camera::work_loop()
{
    while(isRunning)
    {
        {
            std::lock_guard<std::mutex> lk(img_mutex_);
            (*capture_)>>img_;
            isReady_=true;
        }
        img_cv_.notify_one();
        if(onpreviewcb_)
            onpreviewcb_(img_);
        //if here don't sleep,this thread will lock img_mutex_ in all most time,and grapPicture will have not chance to grap image
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    std::cout<<"camera:work_loop end"<<std::endl;
}

可以看到,兩者基本是一樣的,消費者首先要獲得同步鎖,然後wait(wait內部會釋放同步鎖),生產者這時候獲得同步鎖,生產數據,notify,釋放同步鎖(如果不釋放,消費者是無法執行的),這時候消費者在wait處又可以開始執行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章