我担心的是,在线程之间访问全局指针会对全局指针产生什么影响。我的全局指针是线程安全类。当updatethread()
方法使用新指针更新指针并且workerthread()
访问指针时,从代码中将对全局指针产生什么影响。我应该使用哪种同步方式?
SomeCache* ptrCache = NULL;
//worker thread
void Workerthread(std::string strFileToWork)
{
while (std::getline(fileStream, strCurrent))
{
//worker thread accessing the global pointer
if (ptrCache->SearchValue(strCurrent))
{
iCounter++;
}
}
}
void updatethread()
{
//replace old cache with a new fresh updated.
SomeCache* ptrOldCache = ptrCache;
ptrCache = ptrNewCache;
}
答案 0 :(得分:0)
使用App
es的一种可能的解决方案:
var a = [1, 4, 9, 78, 42, 4, 11, 4, 9];
result = [];
verified = [];
for(var i =0; i<a.length; i++){
b = a[i];
temp = {};
temp.value = a[i];
temp.hasDuplicate = false;
temp.positions = [];
temp.differenceFromFirstOccurence = [];
if(verified.indexOf(b) === -1){
temp.positions = [i+1];
for(var j = 0; j <a.length; j++){
c = a[j];
if( i !== j && b === c){
temp.hasDuplicate = true;
temp.positions.push(j+1);
}
}
verified.push(b);
result.push(temp);
}
}
for(var i = 0; i < result.length; i++){
if(result[i].hasDuplicate){
firstPosition = result[i]['positions'][0];
for(var j = result[i]['positions'].length-1; j > 0; j--){
diff = result[i]['positions'][j] - firstPosition-1;
result[i].differenceFromFirstOccurence.push(diff);
}
}
result[i].differenceFromFirstOccurence.reverse();
}
console.log(result);
for(var i =0; i < result.length; i++){
if(result[i].hasDuplicate && result[i].differenceFromFirstOccurence.length){
console.log("The first occurence of "+result[i].value+" is at "+ result[i].positions[0]);
for(var j = 1; j < result[i].positions.length; j++){
console.log("The duplicate occurence of "+result[i].value+" is at "+ result[i].positions[j] +" and difference is "+ result[i].differenceFromFirstOccurence[j-1]);
}
}
}
如果编译器不支持模板参数推导,则应明确指定互斥锁类型:Select DateSerial(TYear ,TMonth, TDay) As TDate From NDX_FULL
。
答案 1 :(得分:-2)
行为可能是不确定的,您可以参考有关C ++中 volatile 关键字的答案。 https://stackoverflow.com/a/72617/10443813 如果使用 volatile 关键字,则在执行以下行之前,将使用旧值,而在之后,将使用新值。否则,行为可能取决于编译器或编译标志。
ptrCache = ptrNewCache;