問題是您的代碼中存在爭用條件。從邏輯上看來,你的代碼如下所示:
Open file
Repeat
Read record from file
Check if record exists in table
If no record in table
Add record to table
End repeat
Close file
的競爭條件是,如果你必須在執行兩道工序,每一個可以檢查,看看是否在表中存在一個特定的記錄;兩者都會返回一個表示記錄不存在的返回值;然後雙方將繼續插入記錄。顯然,數據庫中沒有主鍵或唯一鍵約束來防止重複數據,因此每個進程插入的數據都被添加到表中。
您遇到的情況發生是因爲兩個進程不知道對方正在做什麼。每個進程都是獨立調度的,並且不僅在它們之間共享處理器,而且與所有其他進程同時運行,並且它們的執行被不可預知地中斷以允許其他進程運行。現在,讓我們考慮以下情況:
Process 1 starts
Process 2 starts
Process 1 issues an I/O request to read a record from the
file, relinquishing the CPU
Process 2 issues an I/O request to read a record from the
file, relinquishing the CPU
I/O for process 1 completes and process 1 is rescheduled for execution
I/O for process 2 completes and process 2 is rescheduled for execution
Process 2 executes, issues an SQL request to see if the record exists in the
table, and relinquishes the CPU
Process 1 executes, issues the same SQL request, and relinquish the CPU
SQL request for process 2 completes; process 2 is rescheduled for execution
SQL request for process 1 completes; process 1 is rescheduled for execution
Process 1 executes and finds the record does not exist in the file
Process 1 adds the record to the file
Process 2 executes and finds the record does not exist in the file
Process 2 adds the record to the file
請注意,進程的執行順序已經交換了幾次。這是正常的 - 你無法控制哪個進程將被安排執行,你也不需要關心它。
您的每個進程都已正確找到來自該文件的記錄在查看數據庫時不存在並因此添加它。不幸的是,你的每一個進程都不知道另一個進程或多或少地在同一時間執行完全相同的事情。
IMO最容易做的事情是讓每個進程都試圖鎖定文件,以便只讀取文件。這會阻止其他進程讀取和處理文件中的數據,從而防止出現這種問題。它看起來像你使用VB.Net,所以你應該能夠使用FileSystem.Lock來鎖定文件。您的程序的邏輯流程將改爲如下所示:
Open file
Lock the file
- either wait until the file can be locked successfully or terminate because the
file is in use by another process
Repeat
Read record from file
Check if record exists in table
If no record in table
Add record to table
End repeat
Unlock the file
Close file
祝您好運。
查找「比賽條件」。祝你好運。 – 2014-12-05 03:39:19
那麼有什麼解決辦法? – 2014-12-05 08:17:10